欢迎访问移动开发之家(rcyd.net),关注移动开发教程。移动开发之家  移动开发问答|  每日更新
页面位置 : > > > 内容正文

Android连接MySQL数据库实现方法详解,

来源: 开发者 投稿于  被查看 34389 次 评论:132

Android连接MySQL数据库实现方法详解,


目录
  • 前言
  • 实例
  • 常见报错原因
  • 连接缓慢原因

前言

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

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

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

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

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

  • Android连接的MySQL版本应为5.X版本(8.X版本无法使用)驱动程序通用
  • 请注意!!!Android中连接/对数据库操作 只能在子线程进行!!!!(单开一个线程)

因为是耗时操作!!!

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

  • 应为程序添加网络及WIFI权限(通过网络连接数据库)
//必须加
<uses-permission android:name="android.permission.INTERNET"/>
//可不加
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
  • 添加MySQL驱动程序

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

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

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

  • 打开电脑的telnet服务,使其他人可以访问
  • 打开电脑防火墙的MySQL端口,使其他人可以访问
  • 建议以如下格式写连接代码

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

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

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

  • 连接关闭后ResultSet中内容会消失(将其内容在连接关闭前存在其他地方)
  • 读ResultSet内容前先移动指针 .next();如果ResultSet中无搜索结果,.next()方法返回false,有搜索结果返回true。
  • 设置连接MySQL超时 DriverManager.setLoginTimeout(2000);
  • 尽量复用通道,避免反复连接造成延迟!!!
  • ip地址问题

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

  • MySQL其实就是服务器,可以直接进行远程连接,不用再做服务器
  • MySQL自带的4个数据库不能删!!!

information_schema、mysql、performation_schema、test

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

实例

  • ConnectionUtils 连接工具类,用于连接数据库
  • User 存储内容类,用于存储MySQL回传数据
  • 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.setLoginTimer(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();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
//存储内容类
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);
    }
}

常见报错原因

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

连接缓慢原因

  • 程序是否复用通道connection,反复连接数据库会导致缓慢
  • prepareStatement代替statement,减少命令的创建(要复用PreparedStatement)

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

到此这篇关于Android连接MySQL数据库实现方法详解的文章就介绍到这了,更多相关Android连接MySQL内容请搜索3672js教程以前的文章或继续浏览下面的相关文章希望大家以后多多支持3672js教程!

您可能感兴趣的文章:
  • Android连接MySQL数据库详细教程
  • Android连接MySQL数据库并进行增删改查操作示例讲解
  • Android实现与Apache Tomcat服务器数据交互(MySql数据库)

用户评论