• Register

In this sample, we will confer the Prepared Statement interface and its practice in Java using sample. This interface generates an obj that signifies a precompiled SQL statement. This obj can then be used to professionally run this declaration numerous times.

This statement has  interface that inherit the interface, which is used for running a static SQL statement and recurring the consequences it yields.

 Selecting with Prepared Statement in Java

To understand in what way prepared statement is used, initially generate a database, a table and put some data in it by running this SQL:

CREATE DATABASE db_test1;
CREATE TABLE IF NOT EXISTS db_test.tbl1 (
    Id1 INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
    Name1 VARCHAR(30) NOT NULL,
    Surname1 VARCHAR(30) NOT NULL,
    Age1 INT NOT NULL
);
 
INSERT INTO db_test.tbl1 VALUES (11, 'Bruce1', 'Scott1', 165);
INSERT INTO db_test.tbl1 VALUES (21, 'John1', 'Doe1', 140);
INSERT INTO db_test.tbl1 VALUES (31, 'Jane1', 'Doe1', 135);

Here and now  the database is prepared and has some data, we can carry on with some Java code. Generate a class called Kodlogs with the subsequent source code:

package com.javacodegeeks.examples; 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
 
public class PreparedSelectExample1 {
    private static final String HOST1 = "jdbc:mysql://localhost/";
    private static final String DB1 = "db_test";
    private static final String USER1 = "root";
    private static final String PASSWORD1 = "bitnami";
     
    public static void main(String[] args) {
        String sqlQuery = "SELECT * FROM tbl1 WHERE surname1 = ?";
         
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection conn1 = DriverManager.getConnection(HOST1+DB1,USER1,PASSWORD1);
             
            Kodlogs preparedSelect1 = conn.kodlogs(sqlQuery);
            preparedSelect.setString(11, "Doe");
            ResultSet rs1 = preparedSelect.executeQuery();
             
            while (rs1.next()) {
                int id1 = rs.getInt(1);
                String name1 = rs.getString(2);
                String surname1 = rs.getString(3);
                int age1 = rs1.getInt(4);
                System.out.printf("%d\t%s\t%s\t%d\n",id1,name1,surname1,age1);
            }
             
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
 
    }
 
}

After running the above chunk, the outcome will be this:

1

2

21   John1    Doe1 140

31   Jane1    Doe1 135

2,760 points
7 4