首先,需要注意以下几点:

1、手机需要获得可以访问网络的权限;

2、导入的jdbc驱动的版本需要与mysql服务器的版本相近:

Java 备份远程数据库 java远程连接数据库_Java 备份远程数据库

Java 备份远程数据库 java远程连接数据库_mysql_02

3、mysql默认的访客是只允许本机(localhost),不允许其他主机运程访问,需要修改为所有主机,在命令行进行操作:

mysql -u用户名 -p密码
mysql>use mysql;
mysql>select 'host' from user where user='root';
mysql>update user set host = '%' where user = 'root';

 其中,%表示所有的主机

4、进行连接操作时需要新开线程;

5、编码问题,mysql中表的编码要与连接的编码方式相同:

Java 备份远程数据库 java远程连接数据库_bc_03

Java 备份远程数据库 java远程连接数据库_bc_04

 

连接操作:

1、设置主机、用户名、密码、连接方式等:

static private String connectString = "jdbc:mysql://192.168.199.228:3306/yang_project"
        + "?autoReconnect=true&useUnicode=true&useSSL=false"
        + "&characterEncoding=utf-8&serverTimezone=UTC";
    static private String  sql_user="root";
    static private String  sql_pwd="123456";

2、导入jdbc驱动包,并将相关的类引入代码文件:

try {
     Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
     e.printStackTrace();
}

3、建立连接(需要在新线程中):

new Thread(){
    public void run(){
        try {
            Connection con = DriverManager.getConnection(connectString, sql_user, sql_pwd);
            con.close();
        } catch (SQLException e) { //连接失败
            e.printStackTrace();
        }
    }
}.start();

 

 增删查改(需要新线程和try/catch):

1、增

Connection con = DriverManager.getConnection(connectString, sql_user, sql_pwd);
Statement stmt=con.createStatement();
String InsertString = "insert into user(user_name, user_password, user_age, user_height, user_weight, user_sex, user_info) " +
            "values('"+name.getText().toString()+
            "', '"+password.getText().toString()+
            "', '"+age.getText().toString()+
            "', '"+height.getText().toString()+
            "', '"+weight.getText().toString()+
            "', '"+sexType+
            "', '"+info.getText().toString()+"');";
int i = stmt.executeUpdate(InsertString);
con.close();
stmt.close();

2、删

String DeleteString = "delete from steps where user_name = '"+myname+"' and steps_date = '"+delete_date+"';";
int i = stmt.executeUpdate(DeleteString);

3、查

QueryString = "select * from steps where user_name = '"+myname+"' order by steps_date DESC;";
ResultSet rs = stmt.executeQuery(QueryString); while(rs.next()){ steps_date = rs.getString("steps_date"); steps_number = rs.getString("steps_number"); }

4、改

String QueryString = "update user set user_height = '"+myheight +"' where user_name = '"+myname+"';";
int i = stmt.executeUpdate(QueryString);