[英]How to insert a row into a that table has an increment id with CachedRowSet?
I'm trying to insert a row into a table that has an increment id with CachedRowSet(I'm using Java wit Java DB), but I got the following SQLException: 我正在尝试向具有CachedRowSet增量ID的表中插入一行(我正在使用Java和Java DB),但是却得到以下SQLException:
java.sql.SQLException: Failed on insert row java.sql.SQLException:插入行失败
at... 在...
SQLState: null SQLState:空
Error Code: 0 错误代码:0
Message: Failed on insert row 消息:插入行失败
Here's my code snippet: 这是我的代码段:
private static String urlString = "jdbc:derby:testdb;create=true";
private static String userName = "testUser";
private static String password = "testPassword";
...
CachedRowSet crs = new CachedRowSetImpl();
crs.setUrl(urlString);
crs.setUsername(userName);
crs.setPassword(password);
crs.setCommand("SELECT * FROM test_table");
crs.execute();
crs.moveToInsertRow();
crs.updateString("str_value", "testValue");
crs.insertRow();
crs.moveToCurrentRow();
crs.acceptChanges();
The SQLException is thrown from crs.inertRow()
. 从
crs.inertRow()
引发SQLException。
The CachedRowSet works well if the table does not have an auto increment id. 如果表没有自动增量ID,则CachedRowSet可以很好地工作。
How can I successfully do this? 我如何成功做到这一点?
other details: 其他详情:
I use the following code to create my table: 我使用以下代码创建表:
conn = DriverManager.getConnection(urlString, userName, password);
Statement stmt = conn.createStatement();
stmt.execute("CREATE TABLE test_table("
+ "id INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),"
+ "str_value VARCHAR(20) NOT NULL,"
+ "CONSTRAINT primary_key PRIMARY KEY (id))");
System.out.println("Talbe test_table created.");
This is a duplicate of Failed on insert row using CachedRowSet . 这是使用CachedRowSet插入行失败的重复。
Unfortunately, that happens because of the API definition : 不幸的是,这是由于API定义而发生的:
Throws: SQLException - if a database access error occurs;
抛出:SQLException-如果发生数据库访问错误。 the result set concurrency is CONCUR_READ_ONLY, this method is called on a closed result set, if this method is called when the cursor is not on the insert row, or if not all of non-nullable columns in the insert row have been given a non-null value
结果集并发性为CONCUR_READ_ONLY,如果在游标不在插入行上时调用此方法,或者未对插入行中的所有非空列都赋予非结果,则在封闭的结果集上调用此方法-空值
You may be better off using JdbcRowSetImpl
. 使用
JdbcRowSetImpl
可能会更好。
You can only stick with the CachedRowSet
if you remove the NOT NULL
constraint of the id
column. 如果删除
id
列的NOT NULL
约束,则只能坚持使用CachedRowSet
。 Unfortunately, this would also mean to remove the PK constraint. 不幸的是,这也意味着要删除PK约束。 I'd assume that is too big a sacrifice, but it's either that or no
CachedRowSet
. 我认为这是一个很大的牺牲,但这不是
CachedRowSet
就是没有。
try this crs.updateNull(1); crs.insertRow();
试试这个
crs.updateNull(1); crs.insertRow();
crs.updateNull(1); crs.insertRow();
where 1 is your PK. 其中1是您的PK。 Worcked for me in MySQL
在MySQL中为我感到烦恼
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.