Код: Выделить всё
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 increment from 0000000001
t char(1) NOT NULL, ----just for insert to get the id
PRIMARY KEY(id)
};
Моя проблема: значение, полученное от getKey(), равно NULL. Я не уверен, почему это происходит, потому что эта функция добавляет новую строку в мою таблицу при каждом запуске, но я не получил значение ключа, а NULL (даже в журнале; но я получаю 1 из columnsCount).
Я копался в 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]
Например: если у меня сегодня 3 вставки, то я вижу 3 строки в таблице (1609060000, 1609060001, 1609060002); на следующий день новые строки будут иметь новую дату начала (1609070000, 1609070001, 1609070002).
Это сложно, но может быть полезно для некоторых областей (но я все равно не могу получить ключ от RETURN_GENERATED_KEYS).
Подробнее здесь: https://stackoverflow.com/questions/393 ... -with-jdbc
Мобильная версия