In this article, we will learn how to insert a record in a MySQL database table using the Java JDBC API. We will use the PreparedStatement interface because the PreparedStatement interface improves performance like SQL statement is precompiled and stored in a PreparedStatement object.
Java
JDBC
JDBC PreparedStatement - Insert a Record Example
In this example, we will use the users database table. Before inserting a record into a database, we need to first create a users table in a database. Here is the article JDBC Statement Create Table Example will create a users table in a mysql_database database.
Here is the Java program to insert data into MySQL database table:
package com.javaguides.jdbc.preparestatement.examples;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* Insert PrepareStatement JDBC Example
*
* @author Ramesh Fadatare
*
*/
public class InsertPStatementExample {
private static final String INSERT_USERS_SQL = "INSERT INTO users" +
" (id, name, email, country, password) VALUES " +
" (?, ?, ?, ?, ?);";
public static void main(String[] argv) throws SQLException {
InsertPStatementExample createTableExample = new InsertPStatementExample();
createTableExample.insertRecord();
}
public void insertRecord() throws SQLException {
System.out.println(INSERT_USERS_SQL);
// Step 1: Establishing a Connection
try (Connection connection = DriverManager
.getConnection("jdbc:mysql://localhost:3306/mysql_database?useSSL=false", "root", "root");
// Step 2:Create a statement using connection object
PreparedStatement preparedStatement = connection.prepareStatement(INSERT_USERS_SQL)) {
preparedStatement.setInt(1, 1);
preparedStatement.setString(2, "Tony");
preparedStatement.setString(3, "tony@gmail.com");
preparedStatement.setString(4, "US");
preparedStatement.setString(5, "secret");
System.out.println(preparedStatement);
// Step 3: Execute the query or update query
preparedStatement.executeUpdate();
} catch (SQLException e) {
// print SQL exception information
printSQLException(e);
}
// Step 4: try-with-resource statement will auto close the connection.
}
public static void printSQLException(SQLException ex) {
for (Throwable e: ex) {
if (e instanceof SQLException) {
e.printStackTrace(System.err);
System.err.println("SQLState: " + ((SQLException) e).getSQLState());
System.err.println("Error Code: " + ((SQLException) e).getErrorCode());
System.err.println("Message: " + e.getMessage());
Throwable t = ex.getCause();
while (t != null) {
System.out.println("Cause: " + t);
t = t.getCause();
}
}
}
}
}
Output
In the above example, we are connecting to the MySQL database with the below line of code:
try (Connection connection = DriverManager .getConnection("jdbc:mysql://localhost:3306/mysql_database?useSSL=false", "root", "root");
Comments
Post a Comment