简体   繁体   中英

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 . 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. 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 . So when I ran that I got this error message: 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, ?, ?, ?, ?)";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM