You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

GridDB JDBC驱动抛出JDBC_OPTIONAL_FEATURE_NOT_SUPPORTED错误原因

解决方案

提供两种可行的替代方案来获取自动生成的主键:

方案1:使用GridDB原生Java API

GridDB原生API支持插入数据后直接返回包含生成主键的Row对象,无需依赖JDBC的getGeneratedKeys():

import com.toshiba.mwcloud.gs.*;
import java.util.Properties;

public class GridDBIdentityExample {
    public static void main(String[] args) throws GSException {
        // 配置连接参数
        Properties props = new Properties();
        props.setProperty("notificationMember", "Farwa:20001");
        props.setProperty("user", "GridDB");
        props.setProperty("password", "admin786");

        // 连接GridDB并获取容器(对应SQL表)
        try (GridStore store = GridStoreFactory.getInstance().getGridStore(props);
             Container<Row> container = store.getContainer("Customers")) {

            // 创建Row对象,仅设置非自增列
            Row row = container.createRow();
            row.setString("Customer_Name", "Ali");

            // 插入数据并获取带生成主键的Row
            Row insertedRow = container.put(row);
            int generatedId = insertedRow.getInt("Customer_ID");
            System.out.println("Generated Key: " + generatedId);
        }
    }
}

方案2:使用SQL查询获取最后生成的ID

在INSERT执行完成后,立即在同一会话中执行SELECT @@IDENTITY查询,获取当前会话最后生成的IDENTITY值:

import java.sql.*;

public class JDBCIdentityExample {
    public static void main(String[] args) throws SQLException {
        String url = "jdbc:gs://Farwa:20001/default";
        String user = "GridDB";
        String password = "admin786";

        try (Connection connection = DriverManager.getConnection(url, user, password)) {
            connection.setAutoCommit(false); // 开启事务确保同一会话

            // 执行INSERT(省略自增列,让数据库自动生成)
            String insertSql = "INSERT INTO Customers (Customer_name) VALUES (?)";
            try (PreparedStatement insertStmt = connection.prepareStatement(insertSql)) {
                insertStmt.setString(1, "Ali");
                insertStmt.executeUpdate();
            }

            // 查询最后生成的主键
            String selectSql = "SELECT @@IDENTITY AS generated_id";
            try (PreparedStatement selectStmt = connection.prepareStatement(selectSql);
                 ResultSet rs = selectStmt.executeQuery()) {
                if (rs.next()) {
                    int generatedId = rs.getInt("generated_id");
                    System.out.println("Generated Key: " + generatedId);
                }
            }

            connection.commit();
        }
    }
}

关键注意事项

  • 必须删除INSERT语句中对Customer_ID的显式赋值,否则IDENTITY列的自增逻辑不会触发。
  • 使用SELECT @@IDENTITY时,必须保证INSERT和SELECT操作在同一个数据库会话中(通过事务或保持连接未关闭实现),避免获取到其他会话生成的ID。

内容的提问来源于stack exchange,提问作者Farwa Waheed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 12:50:55