Reuse PreparedStatement and pass in different parameter in Java
Description
The following code shows how to reuse PreparedStatement and pass in different parameter.
Example
/*from w w w . ja v a 2s. co m*/
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 {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbctutorial",
"root", "root");
String sql = "SELECT * FROM product WHERE year_made = ?";
PreparedStatement prest = con.prepareStatement(sql);
prest.setInt(1, 2002);
ResultSet rs1 = prest.executeQuery();
while (rs1.next()) {
String mov_name = rs1.getString(1);
int mad_year = rs1.getInt(2);
System.out.println(mov_name + "\t- " + mad_year);
}
prest.setInt(1, 2003);
ResultSet rs2 = prest.executeQuery();
while (rs2.next()) {
String mov_name = rs2.getString(1);
int mad_year = rs2.getInt(2);
System.out.println(mov_name + "\t- " + mad_year);
}
}
}