Java JDBC PreparedStatement set string to select statement

Description

Java JDBC PreparedStatement set string to select statement

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

public class Main {

   public static void queryDbRecipe(Connection conn){
      String sql = "SELECT ID, RECIPE_NUM, NAME, DESCRIPTION " +
                   "FROM RECIPES " +
                   "WHERE RECIPE_NUM = ?";
      PreparedStatement pstmt = null;
      try {//www.j  a v a2  s  . c  o m
          pstmt = conn.prepareStatement(sql);
          pstmt.setString(1, "1001");
          ResultSet rs = pstmt.executeQuery();
          while(rs.next()){
              System.out.println(rs.getString(2) + ": " + rs.getString(3) + 
                              " - " + rs.getString(4));
          }           
      } catch (SQLException ex) {
          ex.printStackTrace();
      } finally {
          if (pstmt != null){
              try {
                  pstmt.close();
              } catch (SQLException ex) {
                  ex.printStackTrace();
              }
          }
      }
      
  }
}



PreviousNext

Related