Logo
JDBC Driver

Overview #

DBPlusEngine-Driver provides a JDBC driver, and it permits users to use ShardingSphere by configuration updates only, without requiring any code changes.

Usage #

Import Maven Dependency #

<dependency>
    <groupId>com.sphere-ex</groupId>
    <artifactId>shardingsphere-jdbc-core</artifactId>
    <version>${shardingsphere.version}</version>
</dependency>

Driver Usage #

Native Driver Usage #

Class.forName("org.apache.shardingsphere.driver.ShardingSphereDriver");
String jdbcUrl = "jdbc:shardingsphere:classpath:config.yaml";

String sql = "SELECT i.* FROM t_order o JOIN t_order_item i ON o.order_id=i.order_id WHERE o.user_id=? AND o.order_id=?";
try (
        Connection conn = DriverManager.getConnection(jdbcUrl);
        PreparedStatement ps = conn.prepareStatement(sql)) {
    ps.setInt(1, 10);
    ps.setInt(2, 1000);
    try (ResultSet rs = preparedStatement.executeQuery()) {
        while(rs.next()) {
            // ...
        }
    }
}

Database Connection Pool Usage #

String driverClassName = "org.apache.shardingsphere.driver.ShardingSphereDriver";
String jdbcUrl = "jdbc:shardingsphere:classpath:config.yaml";

// 以 HikariCP 为例 
HikariDataSource dataSource = new HikariDataSource();
dataSource.setDriverClassName(driverClassName);
dataSource.setJdbcUrl(jdbcUrl);

String sql = "SELECT i.* FROM t_order o JOIN t_order_item i ON o.order_id=i.order_id WHERE o.user_id=? AND o.order_id=?";
try (
        Connection conn = dataSource.getConnection();
        PreparedStatement ps = conn.prepareStatement(sql)) {
    ps.setInt(1, 10);
    ps.setInt(2, 1000);
    try (ResultSet rs = preparedStatement.executeQuery()) {
        while(rs.next()) {
            // ...
        }
    }
}

Configuration Explanation #

Driver Class Name #

org.apache.shardingsphere.driver.ShardingSphereDriver

URL Configuration Explanation #

  • Use jdbc:shardingsphere: as the prefix
  • Configuration file: xxx.yaml, keep consistent format with YAML Configuration
  • Configuration file loading rule:
    • No prefix for loading from the absolute path
    • Prefix with classpath: for loading from the java classpath