1.首先在androidstudio下导入 mysql-connector-java-5.1.8-bin.jar 的jar包
implementation files('C:\\mysql-connector-java-5.1.38.jar')
2.确定MySQL开启远程权限
[root@izbp10fk8pd9zjv9y2g9ajz etc]# mysql -u root -p
Enter password:
use mysql;
select host from user where user='root';
update user set host = '%' where user ='root';
#刷新配置。
flush privileges;
#完成权限远程访问权限配置
MainActiviry.java
package com.example.xeonrnc.cloud;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new Runnable() {
@Override
public void run() {
DBConnection.linkMysql();
}
}).start();
}
}
DBConnection.java
package com.example.xeonrnc.cloud;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class DBConnection {
private static final String driver = "com.mysql.jdbc.Driver";
// private static final String url = "jdbc:mysql://192.168.43.173:3306/test?useSSL=true&serverTimezone=GMT";
private static final String url = "jdbc:mysql://云端公网ip:3306/数据库名称";
private static final String user = "root";
private static final String pwd = "密码";
public static void linkMysql() {
Connection conn=null;
PreparedStatement stmt=null;
try {
Class.forName(driver).newInstance();
System.out.println("驱动加载成功!!!!!");
}
catch (Exception e){
e.printStackTrace();
}
try{
conn = DriverManager.getConnection(url,user,pwd);
System.out.println("连接数据库成功!!!!!!");
String sql = "select * from user";
stmt= conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
while (rs.next()){
String id=rs.getString("id");
String name=rs.getString("name");
String phone=rs.getString("phone");
System.out.println(id+"\t"+name+"\t"+phone);
}
} catch (Exception e) {
e.printStackTrace();
}
finally {
if(conn!=null){
try {
conn.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
}
}