【问题标题】:Cannot get auto generated ID from MSSQL with JDBC无法使用 JDBC 从 MSSQL 获取自动生成的 ID
【发布时间】:2016-09-06 10:48:14
【问题描述】:
    public String getKey() {

    Connection con = null;
    Statement stmt = null;
    String generatedKey = null;
    try {
        con = dataSrc.getConnection();
        stmt = con.createStatement();

        // ask to return generated key
        int affectedRows = stmt.executeUpdate("Insert into CountTab(t) value('0')",
                Statement.RETURN_GENERATED_KEYS);

        if (affectedRows == 0) {
            throw new SQLException(
                    "Creating row failed, no rows affected.");
        }

        try (ResultSet generatedKeys = stmt.getGeneratedKeys()) {
             ResultSetMetaData rsmd = generatedKeys.getMetaData();
             int columnCount = rsmd.getColumnCount();

             if (Log4j.log.isEnabledFor(Level.INFO)) {
                    Log4j.log.info("count: " + columnCount);
            }

            if (generatedKeys.next()) {
                generatedKey = generatedKeys.getString(1);

                if (Log4j.log.isEnabledFor(Level.INFO)) {
                    Log4j.log.info("key: " + generatedKey);
                }
            } else {
                throw new SQLException(
                        "Creating row failed, no ID obtained.");
            }
        }

    } catch (SQLException se) {

        // Handle any SQL errors
        throw new RuntimeException("A database error occured. "
                + se.getMessage());

    } finally {

        // Clean up JDBC resources
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException se) {
                se.printStackTrace(System.err);
            }
        }
        if (con != null) {
            try {
                con.close();
            } catch (Exception e) {
                e.printStackTrace(System.err);
            }
        }

    }
    return generatedKey;

}

CountTab{---this is my table(designed by other)
    id char(10) NOT NULL, ----Auto increament from 0000000001
    t char(1) NOT NULL,   ----just for insert to get the id
    PRIMARY KEY(id)
};

我正在尝试使用 java 1.7.0 来获取从 MS SQL DB 生成的唯一 ID,上面的代码就是我用来执行此操作的;我还从 MSDN 获得了 sqljdbc_4.1.5605.100,并将 jar 添加到我的程序的类路径中。

我的问题:我从 getKey() 得到的值是 NULL。我不确定为什么会发生这种情况,因为这个函数在每次运行时都会在我的表中添加新行,但它没有回复我 Key 值而是 NULL(即使在 Log 中;但我确实从 columnCount 得到 1)。

我在 Stackoverflow 上进行了挖掘,但没有看到任何类似或符合我情况的答案。如果有任何解决方案,请帮助我。

==============

更新:

这是表架构

CREATE TABLE [CountTab](
[id] [char](10) NOT NULL,
[t] [char](1) NOT NULL,
CONSTRAINT [PK_CountTab] PRIMARY KEY CLUSTERED 
(
    [id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

我想我可能知道他/她为什么要制作这样的表格:因为 ID 需要以日期形式开头,例如 yyMMddxxxx

例如:如果我今天有 3 条插入,那么我可以在表中看到 3 条记录(1609060000、1609060001、1609060002);第二天,新记录将有新的开始日期(1609070000、1609070001、1609070002)。

这很棘手,但可能对某些领域有用(但我仍然无法从 RETURN_GENERATED_KEYS 获取密钥)。

【问题讨论】:

  • 我想知道您没有遇到异常。因为 Count 是 SQL 中的关键字。请重命名您的表格
  • @Jens 是的,我重命名了它。
  • @Paolo 并且不,我确实从那里得到了代码,但它没有像它所说的那样回复我的 KEY。所以这和那不一样。
  • edit 您的问题添加exact create table 语句为有问题的表。 char(10) 不能是 SQL Server 中的“自动增量”列

标签: java sql-server jdbc mssql-jdbc


【解决方案1】:

没关系,我创建了另一个具有自动增量标识的表,RETURN_GENERATED_KEYS 现在可以工作了。看起来它不支持不是身份的Key。

【讨论】:

    猜你喜欢
    • 2015-09-20
    • 1970-01-01
    • 1970-01-01
    • 2016-04-01
    • 2019-08-12
    • 1970-01-01
    • 1970-01-01
    • 2010-12-29
    • 1970-01-01
    相关资源
    最近更新 更多