连接数据库的代码如下所示
public class DBHelper {
private static final String TAG = "mysql11111";
private static Connection conn=null;
public static Connection getConnection(){
final Thread thread =new Thread(new Runnable() {
@Override
public void run() {
while (!Thread.interrupted()) {
// 1.加载JDBC驱动
try {
Class.forName("com.mysql.jdbc.Driver");
Log.v(TAG, "加载JDBC驱动成功");
} catch (ClassNotFoundException e) {
Log.e(TAG, "加载JDBC驱动失败");
return;
}
// 2.设置好IP/端口/数据库名/用户名/密码等必要的连接信息
String ip = "192.168.0.105";//10.0.2.2
int port = 3306;
String dbName = "db";
String url = "jdbc:mysql://" + ip + ":" + port
+ "/" + dbName+"?characterEncoding=UTF-8&useSSL=false";
// 构建连接mysql的字符串
String user = "root";
String password = "123456";
// 3.连接JDBC
try {
conn = DriverManager.getConnection(url, user, password);
Log.d(TAG, "数据库连接成功"+conn);
//conn.close();
return;
}
catch (SQLException e) {
Log.e(TAG, e.getMessage());
}
}
}
});
thread.start();
return conn;
}
/**
* 关闭数据库
* */
public static void closeAll(Connection conn, PreparedStatement ps) {
if (conn != null) {
try {
conn.close();
Log.d(TAG, "数据库已关闭");
} catch (SQLException e) {
e.printStackTrace();
}
}
if (ps != null) {
try {
ps.close();
Log.d(TAG, "prepare已关闭");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void insert(String name, String password) {
// 插入数据的 sql 语句
String sql = "insert into db.user (name, password) values (?, ?)";
Connection connection = getConnection();
if(connection==null){
Log.d(TAG, "未连接");
}
PreparedStatement ps = null;
try {
ps = connection.prepareStatement(sql);
// 为两个 ? 设置具体的值
ps.setString(1, name);
ps.setString(2, password);
Log.d(TAG, "1234567");
// 执行语句
ps.executeUpdate();
Log.d(TAG, "添加成功");
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBHelper.closeAll(connection,ps);
}
}
public static boolean check(String name, String password) {
String sql = "select * from db.user where name=? and password=?";
Connection con = getConnection();
PreparedStatement ps=null;
if(con==null){
Log.d(TAG, "未连接");
}
try {
ps=con.prepareStatement(sql);
ps.setString(1,name);
ps.setString(2,password);
Log.d(TAG, ps.toString());
if(ps.executeQuery().next()){
return true;
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
DBHelper.closeAll(con,ps);
}
return false;
}
}
可以成功连接到数据库,如下图
但是登录时调用check就会报错,但是打印出来prepareStatement的sql语句并没有问题,如下图
目前可以确定的是:
(1)已经设置了可以远程连接
(2)更改了wait_time到1000000
(3)IP地址、表名、列名没有任何问题
已经找人帮我解决啦!