Query Records Using PreparedStatement in Java

Description

The following code shows how to query Records Using PreparedStatement.

Example


    //  www .j av  a2 s .c om


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

public class Main {
  public static void main(String[] argv) throws Exception {
    int count = 0;
    Class.forName("com.mysql.jdbc.Driver");
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbctutorial",
        "root", "root");

    String sql = "SELECT title,year_made FROM product WHERE year_made >= ? AND year_made <= ?";
    PreparedStatement prest = con.prepareStatement(sql);
    prest.setInt(1, 2000);
    prest.setInt(2, 2009);
    ResultSet rs = prest.executeQuery();
    while (rs.next()) {
      String mov_name = rs.getString(1);
      int mov_year = rs.getInt(2);
      count++;
      System.out.println(mov_name + "\t" + "- " + mov_year);
    }
    System.out.println("Number of records: " + count);
    prest.close();
    con.close();
  }
}




















Home »
  Java Tutorial »
    JDBC »




Batch
Binary Data
Database
Date Time
Insert
ResultSet
SQL
Statement
Stored Function
Table