Android连接Mysql数据库等常见问题汇总

1.最重要的写在前面连接url 

正常从javaweb转过来的第一印象连接数据库会使用以下url

private static String url = "jdbc:mysql://localhost:3306/school?characterEncoding=utf-8";

或者将  localhost 改成 127.0.0.1 这些都会导致明明测试类运行的时候可以正常访问数据库数据,但是到手机运行环境的时候却报错!

常见报错提醒是  Connection中的createStatement()方法调用时出现空指针异常

这是因为Android手机的localhost本地默认位置不是电脑,而是手机本身。这时候应该要将url改成以下

private static String url = "jdbc:mysql://10.0.2.2/school?characterEncoding=utf-8";

localhost改成10.0.2.2 这样访问的才是电脑本地的数据库。

以下放一段抄其他大佬的jdbcUtil

public class DBUtil {

    //连接配置
    private static String diver = "com.mysql.jdbc.Driver";

    private static String url = "jdbc:mysql://10.0.2.2/school?characterEncoding=utf-8";

    private static String user = "root";//用户名
    private static String password = "123456";//密码

    /*
     * 连接数据库
     * */
    public static Connection getConn() {
        Connection conn = null;
        try {
            Class.forName(diver);
            conn = (Connection) DriverManager.getConnection(url, user, password);//获取连接
            //TODO 这里的日志如果不注释就会报错
//            Log.e("getConn", "连接成功");
        } catch (ClassNotFoundException e) {
            Log.e("getConn", e.getMessage(), e);
            e.printStackTrace();
        } catch (SQLException e) {
            Log.e("getConn", e.getMessage(), e);
            e.printStackTrace();
        }
        return conn;
    }

    public static void close(Statement state, Connection conn) {
        if (state != null) {
            try {
                state.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void close(ResultSet rs, Statement state, Connection conn) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (state != null) {
            try {
                state.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}

2.AndroidManifest.xml配置数据库连接

关于AndroidManifes.xml我也不太懂,感觉像是一种说明,没有这个说明就是默认禁止的行为。

连接数据库要在配置文件中加上这一句。

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

 3.测试环境

test测试有些包是默认没有的加载的,如果要加载到测试环境当中要在build.gradle中说明。

5.连接Mysql所需要的jar包

这个提供的jar包是5.1.1的,需要的酌情下载

链接:https://pan.baidu.com/s/18Y52qE9_-gqdqQNwrSqFcg 
提取码:1145

猜你喜欢

转载自blog.csdn.net/i__saber/article/details/129341135