Android uses JDBC database connection

Andrews database connection is almost inevitable in the development of a work, a little-scale applications often require the use of a database to store user data. For local database SQLite course be used, and for multi-user online application, it is generally required with a cloud database. The more common and open source is Mysql, Mysql in general to be lightweight and easy to use. So In this article we will explain, how in the development of Android, connect to Mysql database.

This article assumes Mysql environment has been configured, you first need to download the connector / J Jar package. Maven repository to be downloaded, download address https://mvnrepository.com/artifact/mysql/mysql-connector-java ; or added to the respective packets directly gradle

compile group: 'mysql', name: 'mysql-connector-java', version: '8.0.16'

Let's create a data connection type DbUtil.java.

public class DbUtil {

    public static String IP = "192.168.2.157"; //数据库IP

    @SuppressLint("NewApi")
    public static Connection createConnection() {

        String DB_NAME = "**";          //数据库名
        String DB_USERNAME = "**";    //  用户名
        String DB_PASSWORD = "**";  //密码

        StrictMode.ThreadPolicy policy = new                   StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        Connection conn = null;

        try {
            Class.forName("com.mysql.jdbc.Driver");
            String connURL = "jdbc:mysql://" + IP + ":3306/" + DB_NAME + "?useUnicode=true&characterEncoding=utf8";
            conn = DriverManager.getConnection(connURL, DB_USERNAME, DB_PASSWORD);
        } catch (SQLException se) {
            Log.e("ERRO", se.getMessage());
        } catch (ClassNotFoundException e) {
            Log.e("ERRO", e.getMessage());
        } catch (Exception e) {
            Log.e("ERRO", e.getMessage());
        }
        return conn;
    }
}

In general, Java applications connect to the database and is similar to the need to connect the local database, directly through DbUtil.createConnection()to create a connection, of course, do not forget to use try...catchto catch the exception.

Guess you like

Origin www.cnblogs.com/ben-future/p/jdbc-mysql.html