赞
踩
第一步,前置工作:
1.配置AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
2.配置build.gradle,这一步如果不写后面写静态方法后执行时会报错
android {
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
compileSdkVersion 30
buildToolsVersion "30.0.0"
3.下载驱动包mysql-connector-java-5.1.49.jar然后复制进libs后add library
这里是个大坑,我之前试过用匹配数据库的版本包8.0.17但一直报错,换成这个版本后就成功连接了
第二步,编程工作
public class DBunit { private static String TAG = "rime"; private static final String dbName = "test"; /*ip为数据库所在服务器的ip地址*/ private static final String ip = "192.168.1.7"; private static final String port = "3306"; private static String url = "jdbc:mysql://" + ip + ":" + port + "/" + dbName; private static final String user = "root"; private static final String password = "root"; public static void connectSQL() { new Thread(new Runnable() { @Override public void run() { Connection conn = null; try { Class.forName("com.mysql.jdbc.Driver"); Log.d(TAG,"驱动加载成功"); conn = DriverManager.getConnection(url,user,password); Log.d(TAG,"数据库连接成功"); String sql="select name from student"; Statement st=(Statement)conn.createStatement(); ResultSet rs=st.executeQuery(sql); while(rs.next()){ String name=rs.getString("name"); Log.i("Mainactivity",name); } conn.close(); st.close(); rs.close(); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); Log.d(TAG,"数据库连接失败"); } } }).start(); } } 注意事项:数据库连接的代码必须写在新开辟的线程里。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。