12 - JDBC Prepared Statement vs Statement. : Page 2 of 2

d. Using Prepared Statement instead of Statement will also handles the SQL injections and we need not to do manual escaping. Let’s write code to use Prepared Statement.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

public class SQLInjectionExample {

    public static void main(String args[])
    {
        try
        {

            Scanner scanner = new Scanner(System.in);
            System.out.println("Enter name:");
            String name = scanner.nextLine();
            Connection conn= getConnection();

            String sql = "select * from user where name=?";

            PreparedStatement stmt = conn.prepareStatement(sql);
            stmt.setString(1, name);            
            ResultSet rs   = stmt.executeQuery();

            while(rs.next())
            {
                String userName=rs.getString("name");
                String age=rs.getString("age");
                String email= rs.getString("email");
                System.out.println("Name= " + userName + " age = " + age + " email= " + email );                
            } 

                stmt.close();
                conn.close();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }

    private static Connection getConnection() {

        Connection con = null;
        String dbDriver = "com.mysql.jdbc.Driver";
        String dbUsername = "root";
        String dbPassword="password";
        String dbHostname="localhost";
        String dbPort="3306";
        String schema="JdbcTutorial";
        try {
                String     url = "jdbc:mysql://"+dbHostname+":"+dbPort+"/"+schema;
                Class.forName(dbDriver);
 
                con = DriverManager.getConnection(url, dbUsername, dbPassword);
        }
        catch (ClassNotFoundException ex1)
        {
            System.out.println("Failed to find driver class " + ex1.getMessage());
            System.exit(1);
        }
        catch (SQLException ex2) {
            System.out.println("Connection failed " + ex2.getMessage());
            System.exit(2);
        }
        return con;
    }
}

 On running program we can see code is not vulnerable to SQL injections    

Avoiding SQL injection with prepared statement

12.4 Performance of Statement vs Prepared Statement

There is also a difference in terms of performance between Statement and Prepared Statement. PreparedStatement are precompiled statements and they gets compiled at a database level which means that parsing of a SQL, all the checks like table name, column names , data types takes place once when we obtain the object of Prepared Statement. Remember we discussed in API section that PreparedStatement takes SQL while obtaining it where as in Statement Checks, compilation takes place on every query execution.

Along with that, Prepared Statement also caches the query plan like what all indexes to be used, constraints and all and this will help in performance gain. 


 

Like us on Facebook