Android Studio link database (MySQL) steps and problems

1. Steps

1. Add jdbc to libs, right click and select Add As Library
insert image description hereinsert image description here
2. Set network permissions in manifests.

insert image description here
write down

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

3. Android 4.0 and later versions do not support time-consuming operations in the main thread, and a new thread must be opened for database operations.
Simple example: (the specific application involves thread data transfer)

new Thread(new Runnable() { @Override public void run() { String CLS="com.mysql.jdbc.Driver"; String URL="jdbc:mysql://IP address: 3306/database name?serverTimezone=UTC "; String USER="Database Username"; String PWD="Database Password"; String test=""; try { Class.forName(CLS).newInstance(); Connection conn=(Connection) DriverManager.getConnection(URL, USER,PWD); String sql=“sql statement to be executed”; Statement stmt=conn.createStatement(); ResultSet rs=stmt.executeQuery(sql); while (rs.next()){ test+=rs.getString( "name"); Log.v("debug", "AAAA"); Log.v("debug",test); }


















} catch (ClassNotFoundException | SQLException | IllegalAccessException | InstantiationException e) {
e.printStackTrace();
}
}
}).start();

4. Because Android runs on the emulator, the ip to access the database cannot be 127.0.0.1 or localhost, it should be the IP address of the host, you can use win + r to enter cmd and use ipconfig to query the local IP.
insert image description here
5. Mysql users must ensure that they have permission to access remotely (users must end with @%, how to operate can be Baidu). Whether
remote access can be tested with navicat, the picture below shows a root user without permission
insert image description here

2. Problems encountered

1. Carefully check the versions of mysql and jdbc. Generally, mysql 5.6 can use some jdbc such as mysql-connector-java-5.1.8. But I tried mysql8.0+ version and 8.0+ jdbc to connect to the database and the app crashed. MySQL 8.0+ can also use a lower version of jdbc.

Use jdbc5+

Class.forName(“com.mysql.jdbc.Driver”);

Use jdbc8+, modify to

Class.forName(“com.mysql.cj.jdbc.Driver”);

2. Be sure to pay attention to the problem of remote access permissions (above)
3. Use a thread other than the main thread to access the database (above)

Guess you like

Origin blog.csdn.net/Salvator_/article/details/128364659