Android连接MySQL数据库

注意:

1. 要为MySQL添加 非root用户 设置权限一定要设置权限!!!默认是没有权限的!!!

请注意为用户设置主机时,主机设置为%时表示通配符,即任何主机均可使用本用户连接,但不能使用localhost(但可以使用本机ipv4地址连接),想使用localhost连接需将用户主机设置为localhost。

Android连MySQL因为不确定连接地址,所以用户主机要设置为%

2. 在Android中连接MySQL的目标ip不能用 //localhost 或 //127.0.0.1 应使用真实的ip地址

(可用cmd查询本机ip,cmd->ipconfig)

3. Android连接的MySQL版本应为5.X版本(8.X版本无法使用)驱动程序通用

4. 请注意!!!Android中 连接/对数据库操作 只能在子线程进行!!!!单开一个线程

因为是耗时操作!!!

如果url、账号、密码正确还报错大概率是没有在子线程操作数据库。

5. 应为程序添加网络及WIFI权限(通过网络连接数据库

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

//可不加
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>

6. 添加MySQL驱动程序

将JAR程序放入Project视图模式下 app/libs中,并右键->Add As Library

7. 在url后加入如下语句能避免许多麻烦

"?useUnicode=true&characterEncoding=utf-8&useSSL=false"

8. 打开电脑的telnet服务,使其他人可以访问

9. 打开电脑防火墙的MySQL端口,使其他人可以访问

10. 建议以如下格式写连接代码

    (1)ConnectionUtils 连接工具类,用于连接数据库

    (2)User  存储内容类,用于存储MySQL回传数据

    (3)UserDao  数据访问对象,执行SQL操作返回存储内容类

11. 连接关闭后ResultSet中内容会消失(将其内容在连接关闭前存在其他地方)

12. 读ResultSet内容前先移动指针 .next() 如果ResultSet中无搜索结果,.next()方法返回false,有搜索结果返回true。

13. 设置连接MySQL超时 DriverManager.setLoginTimeout(2000);

14. 尽量复用通道,避免反复连接造成延迟!!!

15. ip地址问题

个人电脑一般在局域网内,其ip为NAT局域网ip,只能被同局域网设备访问,无法直接被其他网络访问,可使用内网穿透软件(如花生壳)进行处理。

16. MySQL其实就是服务器,可以直接进行远程连接,不用再做服务器

17. MySQL自带的4个数据库不能删!!!

information_schema、mysql、performation_schema、test

18. 可以 多人 同时 使用 同个用户名及密码 登录,但不建议

19. MySQL中建议使用PreparedStatement而不是使用Statement,PreparedStatement的执行速度比Statement快并且可以防止SQL注入攻击。在使用PreparedStatement时可以用代替值,然后使用.setString(int index , String value)方法设置?的值,但请注意,PreparedStatement的index起始是1而不是0要复用PreparedStatement!!

实例:

(1)ConnectionUtils 连接工具类,用于连接数据库

(2)User  存储内容类,用于存储MySQL回传数据

(3)UserDao  数据访问对象,执行SQL操作返回存储内容类

//主线程  以监听为例
Thread thread=null;
public void onClick(View view){
      if(thread==null){
          //连接数据库不能在主线程,单开一个线程
          thread=new Thread(new Runnable(){
              User user=UserDao.findUser(1);
          });
      }
}
//连接工具类

public class ConnectionUtils {

    public static Connection getConn(){
        String url="jdbc:mysql://255.255.255.1:3306/databaseName"+"?useUnicode=true&characterEncoding=utf-8&useSSL=false";
        String username="firstUser";
        String password="123456";
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        Connection connection_jdbc = null;
        try {
            DriverManager.setLoginTimeout(2000);
            connection_jdbc= DriverManager.getConnection(url,username,password);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return connection_jdbc;
    }
    public static boolean close(Connection connection){
        if(connection!=null){
            try {
                connection.close();
                return true;
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        return false;
    }
}
//存储内容类

public class User {
    private int id;
    private String username;
    private String password;
    private int storyid;

    public int getId() {
        return id;
    }
    public String getUsername() {
        return username;
    }
    public String getPassword() {
        return password;
    }
    public int getStoryid() {
        return storyid;
    }

    public User(int id,String username,String password,int storyid){
        this.id=id;
        this.username=username;
        this.password=password;
        this.storyid=storyid;
    }
    public String toString(){
        String str="id:"+id+" username:"+username+" password:"+password+" storyid:"+storyid;
        return str;
    }
}
//数据访问对象类

public class Dao {
    private Connection conn;
    public static User findUser(int id){
        //尽量复用通道,避免反复连接造成延迟
        if(conn==null){
            conn=ConnectionUtils.getConn();
        }
        try {
            Statement statement=conn.createStatement();
            String sql="select * from mysql where id ='"+id+"'";
            ResultSet resultSet=statement.executeQuery(sql);
            Boolean bool = resultSet.next();//先移动指针再获取值
            //如果ResultSet无结果,next()返回false
            if(bool){
               int resultSetId=resultSet.getInt("id");
               String resultSetSex=resultSet.getString("sex");
               String resultSetName=resultSet.getString("name");
               User user=new User(resultSetId,resultSetSex,resultSetName);
               return user;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        //确定不使用再关闭通道
        //ConnectionUtils.close(conn);
    }
}

常见报错原因:

1.程序 对/连接 数据库操作 是否在子线程
2.mysql用户主机是否设置%(任意主机)或其他
3.mysql用户权限是否设置
4.程序连接时的用户名与密码是否正确

连接缓慢原因:

1.程序是否复用通道connection,反复连接数据库会导致缓慢
2.prepareStatement代替statement,减少命令的创建(要复用PreparedStatement)。请注意prepareStatement中占位符的索引是从1开始

// Prepared使用例子

// (1) 插入
PreparedStatement preparedStatement=connection.prepareStatement("insert into mysqlTableName (columnName1,columnName2,columnName3) values (?,?,?)" );
preparedStatement.setInt(1,value1);
preparedStatement.setInt(2,value2);
preparedStatement.setInt(3,value3);
preparedStatement.executeUpdate();

// (2) 读取(指定列值的内容)
PreparedStatement preparedStatement=connection.prepareStatement("select * from mysqlTableName where columnName1=? and columnName2=?");
preparedStatement.setInt(1,value1);
preparedStatement.setInt(2,value2);
ResultSet resultSet = preparedStatement.executeQuery();
if(resultSet.next()){
    int i=resultSet.getInt("columnName3");
}

tag: java ,远程连接 ,mysql ,Android ,安卓,MySQL

  • 9
    点赞
  • 43
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

在下嗷呜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值