Files
oceanbase/docs/docs-cn/7.developer-guide-1/6.appendix/1.use-java-to-connect-to-oceanbase.md
2022-02-10 14:51:49 +08:00

2.0 KiB

Java 连接 OceanBase 示例

  1. 添加 Maven 依赖

    <dependency>
    <groupId>com.alipay.oceanbase</groupId>
    <artifactId>oceanbase-client</artifactId>
    <version>1.1.5</version>
    </dependency>
    

    说明

    如果需要下载 oceanbase-client,请点击:oceanbase-client

  1. 修改连接字符串

    连接串的前缀需要设置为 jdbc:oceanbase ,其他部分的使用方式与原生的 MySQL 使用方式保持一致。

    String url = "jdbc:oceanbase://192.168.1.101/TPCC?useUnicode=true&characterEncoding=utf-8";
    String username = "TPCC@obbmsql#obdemo";
    String password = "123456";    
    Connection conn = null;
    try {
        Class.forName("com.alipay.oceanbase.obproxy.mysql.jdbc.Driver");
        conn = DriverManager.getConnection(url, username, password);
        PreparedStatement ps = conn.prepareStatement("select to_char(sysdate,'yyyy-MM-dd HH24:mi:ss') from dual;");
        ResultSet rs = ps.executeQuery();
        rs.next();
        System.out.println("sysdate is:" + rs.getString(1));
        rs.close();
        ps.close();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (null != conn) {
            conn.close();
        }
    }
    

    注意

    • 目前驱动与服务端交互使用的是文本写协议部分,为了兼容 Oracle 文本协议的 SQL 语法,驱动在PreparedStatement 的 setTimestamp() 类型中都会在前面增加 timestamp 的字面量,因此针对 PreparedStatement 模式下,timestamp 参数不支持字面量。

    • ServerPreparedStatement 支持还不完善,因此请不要设置 useServerPrepStmts 和 cachePrepStmts 参数。

    • 对于 Druid 框架,推荐使用 Druid 最新版 1.2.3:https://github.com/alibaba/druid/releases