MySQL的预编译功能
- 执行预编译语句,例如:prepare myfun from 'select * from t_book where bid=?'
- 设置变量,例如:set @str='b1'
- 执行语句,例如:execute myfun using @str
- 设置变量,例如:set @str='b2'
- 执行语句,例如:execute myfun using @str
Connection con = JdbcUtils.getConnection();
Statement stmt = con.createStatement();
stmt.executeUpdate("prepare myfun from 'select * from t_book where bid=?'");
stmt.executeUpdate("set @str='b1'");
ResultSet rs = stmt.executeQuery("execute myfun using @str");
while(rs.next()) {
System.out.print(rs.getString(1) + ", ");
System.out.print(rs.getString(2) + ", ");
System.out.print(rs.getString(3) + ", ");
System.out.println(rs.getString(4));
}
stmt.executeUpdate("set @str='b2'");
rs = stmt.executeQuery("execute myfun using @str");
while(rs.next()) {
System.out.print(rs.getString(1) + ", ");
System.out.print(rs.getString(2) + ", ");
System.out.print(rs.getString(3) + ", ");
System.out.println(rs.getString(4));
}
rs.close();
stmt.close();
con.close();
Connection con = JdbcUtils.getConnection();
String sql = "select * from t_book where bid=?";
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setString(1, "b1");
ResultSet rs = pstmt.executeQuery();
while(rs.next()) {
System.out.print(rs.getString(1) + ", ");
System.out.print(rs.getString(2) + ", ");
System.out.print(rs.getString(3) + ", ");
System.out.println(rs.getString(4));
}
pstmt.setString(1, "b2");
rs = pstmt.executeQuery();
while(rs.next()) {
System.out.print(rs.getString(1) + ", ");
System.out.print(rs.getString(2) + ", ");
System.out.print(rs.getString(3) + ", ");
System.out.println(rs.getString(4));
}
rs.close();
pstmt.close();
con.close();
Connection con = JdbcUtils.getConnection();
String sql = "select * from t_book where bid=?";
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setString(1, "b1");
ResultSet rs = pstmt.executeQuery();
while(rs.next()) {
System.out.print(rs.getString(1) + ", ");
System.out.print(rs.getString(2) + ", ");
System.out.print(rs.getString(3) + ", ");
System.out.println(rs.getString(4));
}
pstmt = con.prepareStatement(sql);
pstmt.setString(1, "b2");
rs = pstmt.executeQuery();
while(rs.next()) {
System.out.print(rs.getString(1) + ", ");
System.out.print(rs.getString(2) + ", ");
System.out.print(rs.getString(3) + ", ");
System.out.println(rs.getString(4));
}
rs.close();
pstmt.close();
con.close();