PreparedStatement是什么?
PreparedStatement叫做预编译声明。它是statement的子接口,可以使用preparedStatement来替代statement。
PreparedStatement的好处,也就是statement的不足。
1.防止SQL攻击,上一篇文章有介绍。
2.提高代码的可读性和可维护性。
3.提高效率。
PreparedStatement的使用
public void login3(String uname,String upwd){
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try{
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/mydb";
String user = "root";
String password = "root";
conn = DriverManager.getConnection(url,user,password);
String sql = "select * from tab_user where username=? and password=?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, uname);//设置第一个问号的值
pstmt.setString(2, upwd);//设置第二个问号的值
rs= pstmt.executeQuery();//注意这里是无参的方法
if(!rs.next()){//如果没有满足条件的记录
System.out.println("登陆失败");
}else{
rs.beforeFirst();
while(rs.next()){
System.out.println(rs.getString(1)+","+rs.getString(2)+","+rs.getString(3));
}
}
}catch(Exception e){
throw new RuntimeException(e);
}finally{
try{
if(rs!=null) rs.close();
if(pstmt!=null) pstmt.close();
if(conn!=null) conn.close();
}catch(Exception e){
throw new RuntimeException(e);
}
}
}
使用conn创建preparedStatement的时候,要先创建一个sql模版。也就是
String sql = "select * from tab_user where username=? and password=?";
SQL模版就是有”?“的SQL语句,?就代表参数。得到preparedStatement对象后,调用setXxx(第几个问号,参数值);也就是
pstmt.setString(1, uname);
这样就可以组合成一条完整的SQL语句。然后再调用executeQuery()方法执行,注意是无参的。如果是insert,update,delete就调用executeUpdate()方法也是无参。因为在创建preparedStatement对象的时候已经将它和一条SQL语句绑定了,并设置参数。所以无需再传入SQL语句。
prepared高效的原因是:
PreparedStatement可以反复使用同一个模版,给予不同的参数来重复使用它。所以在以后的开发中,都去使用preparedStatement,而不使用statement。