/**
* @author wht
*
*/
public class PreparedStatementTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Connection connection=null;
PreparedStatement preparedStatement=null;
ResultSet result=null;
try {
//1注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//2建立数据连接对象
connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/wht?serverTimezone=GMT", "root", "root");
String sql="select * from test where name=?";
//3预编译sql语句并设值
preparedStatement=connection.prepareStatement(sql);
preparedStatement.setString(1, "张三");
// //4执行sql语句
result=preparedStatement.executeQuery();
//5查询结果集
while(result.next()) {
System.out.println(result.getString("name")+":"+result.getString("password"));
}
//6释放资源
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(preparedStatement!=null) {
try {
preparedStatement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
PreparedStatement是预编译sql语句,先把框架弄好,然后再框架里面设置,做到了sql语句和用户的值处于泾渭分明的状态(防止sql注入,把传入的东西都不当成sql语句),虽然现在大部分都用PreparedSta类但Statemen也有自己的价值,如:Statement可以让用户自己写sql语句进行注入(降升序语句),这就是利用了字符串的拼接利用sql注入来达到目的
二者的选择在于你传入的sql语句的东西是个实在的值还是sql语句的词汇