JDBC PreparedStatement example overview:
If you want to execute a Statement object many times, it usually reduces execution time to use a PreparedStatement object instead.
The main feature of a PreparedStatement object is that, unlike a Statement object, it is given a SQL statement when it is created. The advantage to this is that in most cases, this SQL statement is sent to the DBMS right away, where it is compiled. As a result, the PreparedStatement object contains not just a SQL statement, but a SQL statement that has been precompiled. This means that when the PreparedStatement is executed, the DBMS can just run the PreparedStatement SQL statement without having to compile it first.
Below JDBC preparedstatement example insert record to MySQL database table:
package com.javahonk; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; public class JDBCPreparedStatementExample { public static void main(String[] args) { Connection connection = null; PreparedStatement preparedStatement = null; try { // Register JDBC Driver Class.forName("com.mysql.jdbc.Driver"); // Open connection connection = DriverManager.getConnection( "jdbc:mysql://localhost:3306/javahonk", "root", "admin"); // Create query set value and execute statement String sql = "INSERT INTO employee(First_Name, Last_Name)" + " VALUES(?, ?)"; preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, "Java"); preparedStatement.setString(2, "Honk"); preparedStatement.executeUpdate(); System.out .println("Value inserted successfully" + " to employee table"); } catch (Exception e) { e.printStackTrace(); } finally { try { if (connection != null) { connection.close(); } if (preparedStatement != null) { preparedStatement.close(); } } catch (SQLException e) { e.printStackTrace(); } } } }
That’s it for JDBC PreparedStatement example