首先在androidstudio下导入 mysql-connector-java-5.1.8-bin.jar 的jar包
代码:
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();
}
}
}
}
}
选择下面的Run
image.png
我们发现报了个错:
ERROR 1130: Host '112.96.34.130' is not allowed to connect to this MySQL server
解决办法:
登录服务器
mysql -u root -p
然后输入隐藏的密码
进入mysql模式后,mysql> use mysql; (如果你正在使用的数据 库名称是AA ,那么use AA)
然后
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'root' WITH GRANT OPTION;
重新运行程序之后
有可能继续报错:
Access denied for user 'root'@'112.96.34.130' (using password: YES)
听别人说是密码错了,但明明密码是对的还是报错了。只要改一改密码就不会报错了,可能是我的密码使用了特殊符号
在云端修改MySQL登录密码:
停止mysql:service mysql stop
终端输入nano /etc/my.cnf
在[mysqld]的下一行添加skip-grant-tables
image.png
ctrl+x保存,按y保存,然后回车
重启mysql:service mysql restart
输入命令:mysql -u root -p
输入密码之后
mysql> use mysql;
mysql>update user set password=password(‘设置密码’) where user=‘root’;
设置好密码以后
更新权限:mysql>flush privileges;
键入exit,退出mysql
输入命令:nano /etc/my.cnf
把skip-grant-tables删掉
保存以后,重启mysql:service mysql restart
再次运行程序之后
image.png
云端MySQL数据库:
image.png
网友评论