🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Prerequisites
- MySQL database installed.
- MySQL JDBC driver added to your project.
- Basic understanding of Java and JDBC.
Steps
- Set Up Dependencies
- Establish a Database Connection
- Create a Table
- Insert a Record and Retrieve the ID
1. Set Up Dependencies
Ensure you have the MySQL JDBC driver in your classpath. If you are using Maven, add the following dependency to your pom.xml:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
2. Establish a Database Connection
First, we need to establish a connection to the MySQL server using the DriverManager class.
3. Create a Table
We will create a simple table for our example. Here is the SQL statement to create a books table:
CREATE TABLE books (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(100) NOT NULL,
author VARCHAR(100) NOT NULL
);
4. Insert a Record and Retrieve the ID
We'll use the PreparedStatement to insert a record into the books table and retrieve the auto-generated ID.
Example Code
Below is the complete example code demonstrating how to insert a record into a books table and retrieve the ID of the inserted record.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class InsertRecordExample {
// JDBC URL, username, and password of MySQL server
private static final String JDBC_URL = "jdbc:mysql://localhost:3306/your_database?useSSL=false";
private static final String USER = "root";
private static final String PASSWORD = "root";
public static void main(String[] args) {
try (Connection connection = DriverManager.getConnection(JDBC_URL, USER, PASSWORD)) {
System.out.println("Connected to the database");
// Insert a record and get the ID
int insertedId = insertRecord(connection, "The Great Gatsby", "F. Scott Fitzgerald");
System.out.println("Inserted record ID: " + insertedId);
} catch (SQLException e) {
e.printStackTrace();
}
}
private static int insertRecord(Connection connection, String title, String author) throws SQLException {
String insertSQL = "INSERT INTO books (title, author) VALUES (?, ?)";
try (PreparedStatement pstmt = connection.prepareStatement(insertSQL, PreparedStatement.RETURN_GENERATED_KEYS)) {
pstmt.setString(1, title);
pstmt.setString(2, author);
int affectedRows = pstmt.executeUpdate();
if (affectedRows == 0) {
throw new SQLException("Inserting record failed, no rows affected.");
}
try (ResultSet generatedKeys = pstmt.getGeneratedKeys()) {
if (generatedKeys.next()) {
return generatedKeys.getInt(1);
} else {
throw new SQLException("Inserting record failed, no ID obtained.");
}
}
}
}
}
Explanation
-
MySQL Connection:
DriverManager.getConnection(JDBC_URL, USER, PASSWORD)is used to establish a connection to the MySQL server.
-
Inserting a Record:
- The
insertRecord()method inserts a record into thebookstable using aPreparedStatement. PreparedStatement.RETURN_GENERATED_KEYSis used to tell the JDBC driver to return the auto-generated keys.
- The
-
Retrieving the Generated Key:
- After executing the
executeUpdate()method,getGeneratedKeys()is called to retrieve the generated key. - The key is retrieved from the
ResultSetand returned by theinsertRecord()method.
- After executing the
Output
Running the code will produce output similar to the following:
Connected to the database
Inserted record ID: 1
Conclusion
Retrieving the ID of an inserted record in a MySQL database using JDBC is straightforward. By using the RETURN_GENERATED_KEYS flag with a PreparedStatement, you can easily obtain the auto-generated key after executing an insert statement. This approach is essential for operations where the generated key is needed for further processing.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment