Insert Records
In this tutorial, we are going to discuss about how to insert records into table using JDBC. Before going into the program, it is advised to go through JDBC Programming Basic Steps where the meaning of Connection, Statement etc. are discussed.
To insert records into a table using JDBC (Java Database Connectivity), you typically follow these steps:
- Load the JDBC driver.
- Establish a connection to the database.
- Create a SQL INSERT statement.
- Prepare and execute the SQL statement.
- Close the connection.
Here’s a simple example of insert records using JDBC (Java Database Connectivity). In this example, I’ll demonstrate how to connect to a MySQL database and insert records into the table named “employees” with three columns: “id”, “name”, and “salary”.
Here’s a basic example demonstrating how to insert records into a table using JDBC:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class InsertRecordsExample {
public static void main(String[] args) {
// JDBC URL, username, and password for your database
String url = "jdbc:mysql://localhost:3306/employee";
String user = "ashok";
String password = "Ashok@123";
// SQL INSERT statement
String insertSQL = "INSERT INTO employee (id, name, salary) VALUES (?, ?, ?)";
try (Connection connection = DriverManager.getConnection(url, user, password);
PreparedStatement statement = connection.prepareStatement(insertSQL)) {
// Set values for placeholders (?, ?, ?)
statement.setString(1, 87);
statement.setString(2, "Ashok Kumar");
statement.setInt(3, 75000);
// Execute the INSERT statement
int rowsAffected = statement.executeUpdate();
System.out.println(rowsAffected + " row(s) inserted successfully.");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Replace "employee"
, "ashok"
, "Ashok@143"
, "employee"
, "id"
, "name"
, and "salary"
with your actual database name, username, password, table name, and column names respectively.
Ensure that:
- You have the appropriate permissions to insert records into the table in the database.
- Handle exceptions appropriately, especially when dealing with database operations. In this example, I’ve simply printed the stack trace, but in a real application, you would handle exceptions more gracefully, possibly logging them or providing meaningful error messages to the user.
- Use
PreparedStatement
to safely insert values into the SQL statement and avoid SQL injection attacks.
That’s all about the how to insert records into table using JDBC. If you have any queries or feedback, please write us email at contact@waytoeasylearn.com. Enjoy learning, Enjoy Java.!!