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: Rakesh
Author Info:

Rakesh is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. Author of insightful How-To articles for Code2care.

Follow him on: X





























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