Guarding Against SQL Injection with PreparedStatements - Java JDBC

Java examples for JDBC:PreparedStatement

Introduction

PreparedStatements send a precompiled SQL statement to the DBMS rather than a String.

Demo Code

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

public class Main {

  public static void main(String[] args) {
    String sql = "SELECT ID, idBER, RECIPE_NAME, DESCRIPTION "
        + "FROM RECIPES " + "WHERE idBER = ?";

    try (PreparedStatement pstmt = getConnection().prepareStatement(sql)) {

      pstmt.setString(1, "1");
      ResultSet rs = pstmt.executeQuery();
      while (rs.next()) {
        System.out.println(rs.getString(2) + ": " + rs.getString(3) + " - "
            + rs.getString(4));/*from   w w  w  . j ava2s . co  m*/
      }
    } catch (SQLException ex) {
      ex.printStackTrace();
    }
  }

  public static Connection getConnection() throws SQLException {
    Connection conn = null;

    String hostname = null;
    String port = null;
    String database = null;
    String username = null;
    String password = null;
    String driver = null;
    String jndi = null;
    String jdbcUrl;
    if (driver.equals("derby")) {
      jdbcUrl = "jdbc:derby://" + hostname + ":" + port + "/" + database;
    } else {
      jdbcUrl = "jdbc:oracle:thin:@" + hostname + ":" + port + ":" + database;
    }
    conn = DriverManager.getConnection(jdbcUrl, username, password);
    System.out.println("Successfully connected");
    return conn;
  }
}

Related Tutorials