[英]How to set preparedStatement() value of an auto_increment field in MySQL
Please, I have a table called sales
which has 6 columns with the first column being set to be auto_increment
. 拜托,我有一个名为sales
的表,该表有6列,第一列设置为auto_increment
。 That is, I have this table; 也就是说,我有这张桌子。
CREATE TABLE `sales` (
`billno` int(11) NOT NULL AUTO_INCREMENT,
`date` varchar(20) DEFAULT NULL,
`item_code` int(16) DEFAULT NULL,
`item_name` varchar(15) DEFAULT NULL,
`quantity` int(7) DEFAULT NULL,
`amount` int(15) DEFAULT NULL,
PRIMARY KEY (`billno`));
And now in a Java project, I wanna insert some data into 5 fields not taking into consideration billno
, since it's an auto_increment column. 现在在Java项目中,我想将一些数据插入5个字段中而不考虑billno
,因为它是一个auto_increment列。 I searched for a solution to this on the internet but didn't find anything that worked in my case. 我在互联网上搜索了此问题的解决方案,但没有发现任何适合我的情况。
Here's is how I got about this: 这是我的解决方法:
String query = "insert into sales values(?, ?, ?, ?, ?)";
stmtDue = conn.prepareStatement(query);
stmtDue.setString(1, date);
stmtDue.setInt(2, itemCode);
stmtDue.setString(3, prodName);
stmtDue.setInt(4, quantity);
stmtDue.setInt(5, totalPrice);
int rowset = stmtDue.executeUpdate();
This above approach was proposed by coderanch forum . 上述方法是由Coderanch论坛提出的。 So when I ran that I got this error message: Column count doesn't match value count at row 1
. 因此,当我运行该命令时,收到以下错误消息: Column count doesn't match value count at row 1
。
I also tried this: 我也试过这个:
String query = "insert into sales values(DEFAULT, ?, ?, ?, ?, ?)";
stmtDue = conn.prepareStatement(query);
stmtDue.setString(2, date);
stmtDue.setInt(3, itemCode);
stmtDue.setString(4, prodName);
stmtDue.setInt(5, quantity);
stmtDue.setInt(6, totalPrice);
That still didn't work. 那仍然没有用。
Please how can I go about solving this issue? 请问我该如何解决这个问题?
You should specify which columns you are inserting into: 您应该指定要插入的列:
"insert into sales(columnname, columnname, columnname,columnname) values(?, ?, ?, ?)";
and leave out the auto increment column. 并保留“自动递增”列。 The auto increment will be auto incremented. 自动递增将自动递增。
Or you can pass in a zero like this: 或者,您可以像这样传递零:
"insert into sales(autoincrementcolumn, columnname, columnname,
columnname,columnname) values(0, ?, ?, ?, ?)";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.