背景信息

ShardingSphere-JDBC 提供了 JDBC 驱动,可以仅通过配置变更即可使用,无需改写代码。

参数解释

驱动类名称

org.apache.shardingsphere.driver.ShardingSphereDriver

URL 配置

  • jdbc:shardingsphere: 为前缀
  • 配置文件:xxx.yaml,配置文件格式与 YAML 配置一致
  • 配置文件加载规则:
    • 无前缀表示从指定路径加载配置文件
    • classpath: 前缀表示从类路径中加载配置文件

操作步骤

  1. 引入 Maven 依赖
  1. <dependency>
  2. <groupId>org.apache.shardingsphere</groupId>
  3. <artifactId>shardingsphere-jdbc-core</artifactId>
  4. <version>${shardingsphere.version}</version>
  5. </dependency>
  1. 使用驱动
  • 使用原生驱动:
  1. Class.forName("org.apache.shardingsphere.driver.ShardingSphereDriver");
  2. String jdbcUrl = "jdbc:shardingsphere:classpath:config.yaml";
  3. 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=?";
  4. try (
  5. Connection conn = DriverManager.getConnection(jdbcUrl);
  6. PreparedStatement ps = conn.prepareStatement(sql)) {
  7. ps.setInt(1, 10);
  8. ps.setInt(2, 1000);
  9. try (ResultSet rs = preparedStatement.executeQuery()) {
  10. while(rs.next()) {
  11. // ...
  12. }
  13. }
  14. }
  • 使用数据库连接池
  1. String driverClassName = "org.apache.shardingsphere.driver.ShardingSphereDriver";
  2. String jdbcUrl = "jdbc:shardingsphere:classpath:config.yaml";
  3. // 以 HikariCP 为例
  4. HikariDataSource dataSource = new HikariDataSource();
  5. dataSource.setDriverClassName(driverClassName);
  6. dataSource.setJdbcUrl(jdbcUrl);
  7. 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=?";
  8. try (
  9. Connection conn = dataSource.getConnection();
  10. PreparedStatement ps = conn.prepareStatement(sql)) {
  11. ps.setInt(1, 10);
  12. ps.setInt(2, 1000);
  13. try (ResultSet rs = preparedStatement.executeQuery()) {
  14. while(rs.next()) {
  15. // ...
  16. }
  17. }
  18. }

配置示例

加载 classpath 中 config.yaml 配置文件的 JDBC URL:

  1. jdbc:shardingsphere:classpath:config.yaml

加载绝对路径中 config.yaml 配置文件的 JDBC URL:

  1. jdbc:shardingsphere:/path/to/config.yaml