preparedStatement 有三大优点:
一,代码的可读性和可维护性
二,PreparedStatement尽最大可能提高性能,有预编译功能
三,最重要的一点是极大地提高了安全性.
第一点直接看两者代码对比
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
String sql = "insert into hero values(null,?,?,?)";
try (Connection c = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/how2java?characterEncoding=UTF-8","root", "admin");
Statement s = c.createStatement();
PreparedStatement ps = c.prepareStatement(sql);
) {
// Statement需要进行字符串拼接,可读性和维修性比较差
String sql0 = "insert into hero values(null," + "'提莫'" + "," + 313.0f + "," + 50 + ")";
s.execute(sql0);
// PreparedStatement 使用参数设置,可读性好,不易犯错
// "insert into hero values(null,?,?,?)";
ps.setString(1, "大大大多提");
ps.setFloat(2, 313.0f);
ps.setInt(3, 50);
ps.execute();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
第二点主要原因是因为存在预编译能力
https://blog.csdn.net/zhangw1236/article/details/59113941
https://blog.csdn.net/coco0930/article/details/92711179
第三点是防止sql注入
来源:CSDN
作者:zhu1371884551
链接:https://blog.csdn.net/zhu1371884551/article/details/103722473