← Back to Chapters

JDBC Insert Operation

?️ JDBC Insert Operation

? Quick Overview

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.

? Key Concepts

  • JDBC Driver
  • Connection object
  • PreparedStatement
  • SQL INSERT query
  • executeUpdate() method

? Syntax / Theory

To insert data using JDBC, we use the SQL INSERT statement along with PreparedStatement. This helps prevent SQL injection and improves performance.

? Code Example

? View Code Example
// 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();
}
}

? Interactive Simulation

Enter values below to visualize how PreparedStatement sends data to the Database.

☕ Java Application

sql = "INSERT INTO..."

ps.setInt(1, ...)

ps.setString(2, "...")

ps.setInt(3, ...)

?️ MySQL Database (Table: student)

ID Name Age
101 Rahul 22

? Live Output / Explanation

Expected Output

Rows inserted: 1

The record is successfully added to the student table in the database.

✅ Tips & Best Practices

  • Always use PreparedStatement instead of Statement
  • Close database connections properly
  • Handle exceptions using try-catch or throws
  • Never hardcode database credentials in production

? Try It Yourself

  • Insert multiple records using user input
  • Modify the program to use Scanner
  • Change the table structure and test again
  • Try inserting data into another database