JDBC Insert Operation is used to add new records into a database table from a Java application. It is a core concept in Advance Java that allows Java programs to interact with relational databases.
To insert data using JDBC, we use the SQL INSERT statement along with PreparedStatement. This helps prevent SQL injection and improves performance.
// JDBC insert operation using PreparedStatement
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class InsertDemo {
public static void main(String[] args) throws Exception {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/testdb","root","password");
String sql = "INSERT INTO student(id,name,age) VALUES(?,?,?)";
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1,101);
ps.setString(2,"Rahul");
ps.setInt(3,22);
int result = ps.executeUpdate();
System.out.println("Rows inserted: " + result);
con.close();
}
}
Enter values below to visualize how PreparedStatement sends data to the Database.
sql = "INSERT INTO..."
ps.setInt(1, ...)
ps.setString(2, "...")
ps.setInt(3, ...)
| ID | Name | Age |
|---|---|---|
| 101 | Rahul | 22 |
Rows inserted: 1
The record is successfully added to the student table in the database.
PreparedStatement instead of Statement