Insert Auto Increment Value using PreparedStatement in Java JDBC


If you have an auto-increment value in your database table and you are wondering how to insert the value for it while using PreparedStatement, well, simply insert a Java null value!

Example:

Database Table with AUTO_INCREMENT field:
CREATE TABLE `students` (
  `student_id` int NOT NULL AUTO_INCREMENT,
  `student_name` varchar(45) NOT NULL,
  `student_dob` datetime NOT NULL,
  `student_address` varchar(45) NOT NULL,
  PRIMARY KEY (`student_id`,`student_dob`)
Java Code:
String insertQuery ="insert into students values(?,?,?,?)";
Connection connection = DriverManager.getConnection(url,userName,password);
PreparedStatement preparedStatement = connection.prepareStatement(insertQuery);

preparedStatement.setString(1, null);
preparedStatement.setString(2, "Andy");
preparedStatement.setDate(3, java.sql.Date.valueOf(LocalDate.of(2001, 10, 10)));
preparedStatement.setString(4, "Japan");
int result = preparedStatement.executeUpdate();
Java Auto Increment Field Value Insert using PreparedStatement

As you can see, the value went in as a next-increment without any issue.

-


Have Questions? Post them here!

Top Hashtags:

Advertisements

Advertisements




Advertisements