gpt4 book ai didi

java - Spring JdbcTemplate 无法从 MySQL 获取插入 ID

转载 作者:可可西里 更新时间:2023-11-01 06:55:06 24 4
gpt4 key购买 nike

我正在尝试向 MySQL 表中插入一行并获取它的插入 ID。我知道 MySQL last_insert_id() 函数,但我似乎无法让它工作。目前,我正在尝试使用一个注释为事务的函数,但我只返回 0。我正在使用 Spring 3.1。

    @Transactional (propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
private long insertTransactionRecord
(
int custID,
int porID,
String date,
short crvID
) {
m_template.update ("INSERT INTO " +
" transaction " +
"( " +
" por_id, " +
" cust_id, " +
" trans_date, " +
" crv_id " +
") " +
"VALUES " +
"( " +
" ?, " +
" ?, " +
" ?, " +
" ? " +
")",
new Object[] {
porID,
custID,
date,
crvID
});
return m_template.queryForLong ("SELECT " +
" last_insert_id() " +
"FROM " +
" transaction " +
"LIMIT 1");
}

最佳答案

使用 Spring 的内置支持而不是自己做。

SqlUpdate insert = new SqlUpdate(ds, "INSERT INTO company (name) VALUES (?)");
insert.declareParameter(new SqlParameter(Types.VARCHAR));
insert.setReturnGeneratedKeys(true);
// assuming auto-generated col is named 'id'
insert.setGeneratedKeysColumnNames(new String[] {"id"});
insert.compile();
....
GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
insert.update(new Object[]{"test"}, keyHolder);
System.out.println(keyHolder.getKey().longValue());

关于java - Spring JdbcTemplate 无法从 MySQL 获取插入 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9350867/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com