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.

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org



















Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap