文档

Java访问(2.0版)

更新时间:

本文介绍Java中如何通过MySQL JDBC连接云原生数据仓库AnalyticDB MySQL版2.0集群。

MySQL JDBC驱动版本

AnalyticDB for MySQL支持以下版本的MySQL JDBC驱动。

  • 5.0版本系列:5.0.2,5.0.3,5.0.4,5.0.5,5.0.7,5.0.8。

  • 5.1版本系列:5.1.1,5.1.2,5.1.3,5.1.4,5.1.5,5.1.6,5.1.7,5.1.8,5.1.11,5.1.12,5.1.13,5.1.14,5.1.15,5.1.16,5.1.17,5.1.18,5.1.19,5.1.20,5.1.21,5.1.22,5.1.23,5.1.24,5.1.25,5.1.26,5.1.27,5.1.28,5.1.29,5.1.31, 5.1.32, 5.1.33, 5.1.34。

注意事项

Java中创建MySQL JDBC连接依赖于MySQL-JDBC驱动包,您需要手动将MySQL-JDBC驱动包(mysql-connector-java-x.x.x.jar)加入到CLASSPATH中,否则无法创建MySQL JDBC连接。

不带重试的JDBC连接示例

您可以在业务系统的Java代码中添加以下代码,通过MySQL JDBC连接AnalyticDB for MySQL数据库。

Connection connection = null;
Statement statement = null;
ResultSet rs = null;
try {
    Class.forName("com.mysql.jdbc.Driver");
    //adb_url是AnalyticDB for MySQL实例的连接地址URL,可以在控制台的集群信息页面获取连接URL,3306是端口号。
    //db_name是AnalyticDB for MySQL实例的名称。
    String url = "jdbc:mysql:/adb_url:3306/db_name?useUnicode=true&characterEncoding=UTF-8";
    Properties connectionProps = new Properties();
    //my_access_key_id为阿里云账号或者RAM子账号的AccessKeyId。
    connectionProps.put("user", "my_access_key_id");
    //my_access_key_secret为阿里云账号或者RAM子账号的AccessKeySecret。
    connectionProps.put("password", "my_access_key_secret");
    connection = DriverManager.getConnection(url, connectionProps);
    statement = connection.createStatement();
    String query = "select count(*) from information_schema.tables";
    rs = statement.executeQuery(query);
    while (rs.next()) {
        System.out.println(rs.getObject(1));
    }
} catch (ClassNotFoundException e) {
    e.printStackTrace();
} catch (SQLException e) {
    e.printStackTrace();
} catch (Exception e) {
    e.printStackTrace();
} finally {
    if (rs != null) {
        try {
            rs.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    if (statement != null) {
        try {
            statement.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    if (connection != null) {
        try {
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

带重试的JDBC连接示例

在JDBC中通过配置参数可以实现连接重试机制。

public static final int MAX_QUERY_RETRY_TIMES = 3;
public static Connection conn = null;
public static Statement statement = null;
public static ResultSet rs = null;
public static void main(String[] args) throws ClassNotFoundException {
    //AnalyticDB for MySQL实例的名称。
    String yourDB = "user_db";
    //my_access_key_id为阿里云账号或者RAM子账号的AccessKeyId。
    String username = "my_access_key_id";
    //my_access_key_secret为阿里云账号或者RAM子账号的AccessKeySecret。
    String password = "my_access_key_secret";
    Class.forName("com.mysql.jdbc.Driver");
    //adb_url是AnalyticDB for MySQL实例的连接地址URL,可以在控制台的集群信息页面获取连接URL,3306是端口号。
    String url = "jdbc:mysql://adb_url:3306/" + yourDB + "?useUnicode=true&characterEncoding=UTF-8";
    Properties connectionProps = new Properties();
    connectionProps.put("user", username);
    connectionProps.put("password", password);
    String query = "select id from test4dmp.test limit 10";
    int retryTimes = 0;
      //通过循环自动重试。
    while (retryTimes < MAX_QUERY_RETRY_TIMES) {
        try {
            getConn(url, connectionProps);
            execQuery(query);//执行query。
            break; //query执行成功后,结束整个循环。
        } catch (SQLException e) {
            System.out.println("Met SQL exception: " + e.getMessage() + ", then go to retry task ...");
            try {
                if (conn == null || conn.isClosed()) {
                    retryTimes++;
                }
            } catch (SQLException e1) {
                if (conn != null) {
                    try {
                        conn.close();
                    } catch (SQLException e2) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    // Clear connection resource.
    closeResource();
}
/**
 * Get connection.
 *
 * @param url
 * @param connectionProps
 * @throws SQLException
 */
public static void getConn(String url, Properties connectionProps) throws SQLException {
    conn = DriverManager.getConnection(url, connectionProps);
}
/**
 * Query task execution logic.
 *
 * @param sql
 * @throws SQLException
 */
public static void execQuery(String sql) throws SQLException {
    Statement statement = null;
    ResultSet rs = null;
    statement = conn.createStatement();
    for (int i = 0; i < 10; i++) {
        long startTs = System.currentTimeMillis();
        rs = statement.executeQuery(sql);
        int cnt = 0;
        while (rs.next()) {
            cnt++;
            System.out.println(rs.getObject(1) + " ");
        }
        long endTs = System.currentTimeMillis();
        System.out.println("Elapse Time: " + (endTs - startTs));
        System.out.println("Row count: " + cnt);
        try {
            Thread.sleep(160000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
/**
 * Close connection resource.
 */
public static void closeResource() {
    if (rs != null) {
        try {
            rs.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    if (statement != null) {
        try {
            statement.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    if (conn != null) {
        try {
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
  • 本页导读 (1)
文档反馈