最近在做一个android查询mysql数据库服务器,用的是JDBC,但不知为何在建好的android项目里总是连接不上数据库。自己做的另一个java文件可以本地访问,也可以远程访问,就是建好的项目不行,检查了两天没解决,求高手指点。
public class GetData {
private Connection connection;
private Statement statement;
private ResultSet resultSet;
//建立连接conn()
public void Conn() throws ClassNotFoundException, SQLException {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://10.28.52.193:3306/schedule"; //10.28.52.193 localhost
String user = "honghu";
String password = "920326";
Class.forName(driver);
connection = DriverManager.getConnection(url, user, password);
if (!connection.isClosed()) {
System.out.println("连接成功");
}
}
//查询
public Student find(Integer id) throws SQLException {
Student student = null;
String sql = "select * from student where stunum = 20103174";
statement = (Statement) connection.createStatement();
resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
String name = resultSet.getString("name").toString();
// System.out.println(name);
student = new Student(name);
}
return student;
}}
//这是单元测试里的测试方法
public void testConn(){
GetData getData = new GetData();
try {
getData.Conn();
Log.i(TAG, "连接成功");
} catch (ClassNotFoundException e) {
Log.e(TAG, "失败001");
} catch (SQLException e) {
// TODO Auto-generated catch block
Log.e(TAG, "失败002");
}
}
应该是jar包有没有引用到项目中,或者引用方法不对。最新的adt 18在编译外部jar包的方式发生改变了,build path的方式无效了,正确的做法应该是:在项目上点右键 ->新建一个文件夹libs,找到你需要的驱动包,ctrl+c复制jar包->选中项目列表中的libs文件夹->ctrl+v,jar包自动添加到工程中了。 做个中转,webserver,就可以了