Android 直接链接Mysql
其实相关的代码网上能找到一大堆,但是我根据网上的代码运行后一直报错,会提示
Caused by: java.lang.ClassNotFoundException: Didn't find class "java.sql.SQLType" on path: DexPathList[[zip file "/system/framework/org.apache.http.legacy.boot.jar",...
那么原因主要是因为驱动程序选择了8.0的版本,只需要把JDBC更换成5.0版本即可
implementation 'mysql:mysql-connector-java:5.0.5'
为了方便大家,我把链接和测试查询的代码也贴上吧,注意代码必须是子线程链接
//连接数据库 private static String diver = "com.mysql.jdbc.Driver"; private String url="jdbc:mysql://192.168.1.108:3306/db?useUnicode=true&characterEncoding=utf-8"; private String user="root"; private String password="root"; PreparedStatement statement=null; Statement stat=null; Connection conn=null; private void connectMySQL(){ new Thread(){ @Override public void run() { try { Class.forName(diver); conn = DriverManager.getConnection(url,user,password);//获取连接 if (!conn.isClosed()){ Log.d("2635", "run: success"); } String sql="select Name from tb_product"; Statement st=conn.createStatement(); ResultSet rs=st.executeQuery(sql); while(rs.next()){ String name=rs.getString("Name"); Log.d("2635", "Name: "+name); } conn.close(); st.close(); rs.close(); Log.d("2635", "run: 连接数据库成功"); }catch (Exception ex){ Log.d("2635", "run: "+ ex.getLocalizedMessage()); Log.d("2635", "run: 连接数据库失败"); } } }.start(); }