How to Insert Data into Database Using Java: Simple Guide
To insert data into a database using
Java, use JDBC by creating a Connection, preparing an INSERT SQL statement with PreparedStatement, setting values, and executing it with executeUpdate(). This process safely adds data to your database table.Syntax
Here is the basic syntax to insert data using JDBC in Java:
- Connection: Connects to the database.
- PreparedStatement: Prepares the SQL
INSERTstatement with placeholders. - setXXX methods: Set values for placeholders.
- executeUpdate(): Runs the SQL command to insert data.
- Close resources: Always close
PreparedStatementandConnectionto free resources.
java
Connection conn = DriverManager.getConnection(dbURL, username, password); String sql = "INSERT INTO table_name(column1, column2) VALUES (?, ?)"; PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setString(1, "value1"); pstmt.setInt(2, 123); pstmt.executeUpdate(); pstmt.close(); conn.close();
Example
This example shows how to insert a new user into a users table with id and name columns.
java
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; public class InsertExample { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/mydatabase"; String user = "root"; String password = "password"; String sql = "INSERT INTO users(id, name) VALUES (?, ?)"; try (Connection conn = DriverManager.getConnection(url, user, password); PreparedStatement pstmt = conn.prepareStatement(sql)) { pstmt.setInt(1, 1); // Set id pstmt.setString(2, "Alice"); // Set name int rowsInserted = pstmt.executeUpdate(); System.out.println(rowsInserted + " row(s) inserted."); } catch (SQLException e) { e.printStackTrace(); } } }
Output
1 row(s) inserted.
Common Pitfalls
- Not closing
ConnectionandPreparedStatementcan cause resource leaks. - Using string concatenation to build SQL can cause SQL injection vulnerabilities; always use
PreparedStatement. - Forgetting to load the JDBC driver (in older Java versions) or wrong database URL causes connection failure.
- Mismatch between SQL placeholders and
setXXXmethods leads to errors.
java
/* Wrong way: vulnerable to SQL injection and error-prone */ String sql = "INSERT INTO users(id, name) VALUES (" + id + ", '" + name + "')"; Statement stmt = conn.createStatement(); stmt.executeUpdate(sql); /* Right way: safe and recommended */ String sql = "INSERT INTO users(id, name) VALUES (?, ?)"; PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setInt(1, id); pstmt.setString(2, name); pstmt.executeUpdate();
Quick Reference
Remember these key points when inserting data with Java:
- Use
PreparedStatementto avoid SQL injection. - Always close your database resources.
- Check your database URL, username, and password.
- Handle
SQLExceptionproperly.
Key Takeaways
Use JDBC with PreparedStatement to insert data safely into a database.
Always close your database connections and statements to avoid leaks.
Avoid building SQL queries with string concatenation to prevent SQL injection.
Handle SQLExceptions to catch and fix database errors.
Set the correct values for each placeholder in your SQL statement.