[英]Java Spring JDBC last_insert_id()
I have a web service and a database(MySQL), I made a table called batch which must generate each time I add some value, an unique key. 我有一个Web服务和一个数据库(MySQL),我创建了一个名为batch的表,每次添加一些值(唯一键)时,该表必须生成。
CREATE TABLE batch (
id INT AUTO_INCREMENT PRIMARY KEY,
description VARCHAR(250) NOT NULL
);
This is the code for the database table and here you are what I wrote so far: 这是数据库表的代码,这就是我到目前为止编写的内容:
static final String addBatchIdSql = "INSERT INTO batch" + "(description)" + "VALUES (?)";
static final String getBatchIdSql = "SELECT LAST_INSERT_ID()";
@Override
public int getBatchId() {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String batchIDcreation = dateFormat.format(new Date());
jdbcTemplate.update(addBatchIdSql, batchIDcreation);
SqlRowSet rowSet = jdbcTemplate.queryForRowSet(getBatchIdSql);
while (rowSet.next()) {
System.out.println(rowSet.findColumn("id"));
}
return 0;
}
The problem is that each time I try to get the id it throws exception which states "invalid column name", I have checked the naming properties in my application in general and could not find any issue, what could be wrong here :// 问题是,每次尝试获取ID时,它都会引发异常,指出“无效的列名”,我通常检查了应用程序中的命名属性,但未发现任何问题,这里可能出了问题://
You can try aliasing the column which is returned from your application's call to LAST_INSERT_ID()
: 您可以尝试将应用程序调用
LAST_INSERT_ID()
返回的列作为别名:
static final String getBatchIdSql = "SELECT LAST_INSERT_ID() AS id";
Full code: 完整代码:
static final String addBatchIdSql = "INSERT INTO batch" + "(description)" + "VALUES (?)";
static final String getBatchIdSql = "SELECT LAST_INSERT_ID() AS id";
@Override
public int getBatchId() {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String batchIDcreation = dateFormat.format(new Date());
jdbcTemplate.update(addBatchIdSql, batchIDcreation);
SqlRowSet rowSet = jdbcTemplate.queryForRowSet(getBatchIdSql);
if (rowSet.next()) {
System.out.println(rowSet.findColumn("id"));
}
return 0;
}
Try this because, your id as auto increment, so last insert id is your max id 尝试执行此操作,因为您的ID为自动递增,因此最后一个插入ID为您的最大ID
static final String getBatchIdSql = "SELECT MAX(id) AS id FROM batch";
Total Code: 总代码:
static final String addBatchIdSql = "INSERT INTO batch" + "(description)" + "VALUES (?)";
static final String getBatchIdSql = "SELECT MAX(id) AS id FROM batch";
@Override
public int getBatchId() {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String batchIDcreation = dateFormat.format(new Date());
jdbcTemplate.update(addBatchIdSql, batchIDcreation);
SqlRowSet rowSet = jdbcTemplate.queryForRowSet(getBatchIdSql);
if (rowSet.next()) {
System.out.println(rowSet.findColumn("id"));
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.