Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert using PreparedStatement. How do I auto-increment the ID?

I have a PreparedStatement such as:

 PreparedStatement preparedStatement = connect.prepareStatement("INSERT into employee (id, time, name" + "(?,?,?)",Statement.RETURN_GENERATED_KEYS);
 ResultSet tableKeys = preparedStatement.getGeneratedKeys();
 preparedStatement.executeUpdate();
 tableKeys.next();
 int autoGeneratedID = tableKeys.getInt(1);
 preparedStatement.setInt(1,autoGeneratedID);
 preparedStatement.setTimestamp(2, new java.sql.Timestamp(new java.util.Date().getTime()));                           
 preparedStatement.setString(3, "Test");
 preparedStatement.executeUpdate();

As you can see, the Employee table has an auto-incremented ID. I need to basically add it in automatically using preparedStatement as well. Can someone tell me where I am going wrong and correct me? Right now it just gives me an error related to Statement.

like image 444
gran_profaci Avatar asked Jul 03 '13 01:07

gran_profaci


People also ask

How to get auto increment ID in java?

After adding values of all the records to the batch, execute the batch using the executeBatch() method. pstmt. executeBatch(); Finally, get the auto-incremented keys generated by this PreparedStatement object using the getGeneratedKeys() method.

How to INSERT auto increment ID in MySQL using java?

In MySQL database you can declare a column auto increment using the following syntax. CREATE TABLE table_name( ID INT PRIMARY KEY AUTO_INCREMENT, column_name1 data_type1, column_name2 data_type2, column_name3 data_type3, column_name4 data_type4, ............ ........... );

How do you do PreparedStatement?

A prepared statement is a feature used to execute the same (or similar) SQL statements repeatedly with high efficiency. Prepared statements basically work like this: Prepare: An SQL statement template is created and sent to the database. Certain values are left unspecified, called parameters (labeled "?").


1 Answers

Leave the column out of the INSERT statement entirely. It will be generated by the database engine. Your query should be:

INSERT INTO employee (time, name)
VALUES (?, ?)

Secondly, you have to perform the insert first, then get the keys out of the result.

I believe your code should be:

PreparedStatement preparedStatement = 
    connect.prepareStatement("INSERT into employee (time, name) VALUES (?,?)", 
    Statement.RETURN_GENERATED_KEYS);

preparedStatement.setTimestamp(1, 
    new java.sql.Timestamp(new java.util.Date().getTime()));                           
preparedStatement.setString(2, "Test");

preparedStatement.executeUpdate();

ResultSet tableKeys = preparedStatement.getGeneratedKeys();
tableKeys.next();
int autoGeneratedID = tableKeys.getInt(1);

Note this example does not check the success of the executed statement or the existence of returned keys.

like image 155
lc. Avatar answered Oct 12 '22 01:10

lc.