Hvad med denne enkle måde?!
java.sql.Driver d=new com.mysql.jdbc.Driver();
Jeg undrede mig også over, hvorfor du forbinder til database med sådan på denne måde?! Det er bedre at lade serveren styre det.
Konfigurer først context.xml
(hvis du bruger tomcat) sådan her:
<context>
<Resource name="_ds" auth="Container" type="javax.sql.DataSource"
maxActive="128" maxIdle="32" username="_admin" password="qwerty" driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://127.0.0.1:3306/dbname"/>
</context>
Få derefter en forbindelse fra denne ressource i servlet/etc, sådan her:
public void init() {
try {
_ds = (DataSource) InitialContext.lookup("java:/comp/env/_ds");
} catch (Exception ex) {
}
}
private javax.sql.DataSource _ds;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
try {
/*String driver = "com.mysql.jdbc.Driver";
con = null;
String username = "";
String password = "";
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbName", "root", "password");*/
Connection con=_ds.getConnection();
Statement st = con.createStatement();
ResultSet mar = st.executeQuery("SELECT * FROM table");
Gson gson = new GsonBuilder().create();
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
con.close();
} catch (SQLException e) {
String message = e.getMessage();
}
Forresten, glem ikke at compy MySQL JDBC driver jar-filen i <CATALINA_BASE>/lib
mappe.