问题描述
- 安卓新手用JDBC连接mysql时一直报错
-
抛出异常在logcat提示:驱动连接成功,数据库连接失败Could not find class 'javax.naming.StringRefAddr', referenced from method com.mysql.jdbc.ConnectionPropertiesImpl$ConnectionProperty.storeTo。求大神帮忙,错误围绕好长时间了连接代码
//连接数据库 public static Connection getCon() { Connection conn = null; try { Class.forName("org.gjt.mm.mysql.Driver"); System.out.println("驱动连接成功"); } catch (ClassNotFoundException e1) { // TODO Auto-generated catch block System.out.println("驱动连接失败"); } String dbUrl = "jdbc:mysql://localhost:3306/student"; String username = "root"; String psw = "1234"; try { conn = DriverManager.getConnection(dbUrl,username,psw); } catch (SQLException e) { // TODO Auto-generated catch block System.out.println("数据库连接失败"+e); } return conn; }
解决方案
参考Connecting to MySQL from Android with JDBC
把数据库的部分放到AsyncTask或者Thread里面
public void mysql() {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
thrd1 = new Thread(new Runnable() {
public void run() {
while (!Thread.interrupted()) {
try {
Thread.sleep(100);
} catch (InterruptedException e1) {
}
if (con == null) {
try {
con = DriverManager.getConnection("jdbc:mysql://192.168.1.45:3306/deneme", "ali", "12345");
} catch (SQLException e) {
e.printStackTrace();
con = null;
}
if ((thrd2 != null) && (!thrd2.isAlive()))
thrd2.start();
}
}
}
});
if ((thrd1 != null) && (!thrd1.isAlive())) thrd1.start();
thrd2 = new Thread(new Runnable() {
public void run() {
while (!Thread.interrupted()) {
if (con != null) {
try {
// con = DriverManager.getConnection("jdbc:mysql://192.168.1.45:3306/deneme", "ali", "12345");
Statement st = con.createStatement();
String ali = "'fff'";
st.execute("INSERT INTO deneme (name) VALUES(" + ali + ")");
// ResultSet rs = st.executeQuery("select * from deneme");
// ResultSetMetaData rsmd = rs.getMetaData();
// String result = new String();
// while (rs.next()) {
// result += rsmd.getColumnName(1) + ": " + rs.getInt(1) + "n";
// result += rsmd.getColumnName(2) + ": " + rs.getString(2) + "n";
// }
} catch (SQLException e) {
e.printStackTrace();
con = null;
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
});
}
时间: 2024-11-03 14:39:37