Statement 和 PreparedStatement 的区别:
添加或者更新的时候,尽量使用 PreparedStatement ,而不是使用Statement。
Statement用于执行静态SQL语句,在执行的时候,必须指定一个事先准备好的SQL语句,并且相对不安全,会有SQL注入的风险。
PreparedStatement是预编译的SQL语句对象,sql语句被预编译并保存在对象中, 被封装的sql语句中可以使用动态包含的参数。
使用PreparedStatement对象执行sql的时候,sql被数据库进行预编译和预解析,然后被放到缓冲区,每当执行同一个PreparedStatement对象时,他就会被解析一次,但不会被再次编译 可以重复使用,可以减少编译次数,提高数据库性能
且能够避免SQL注入,相对安全(把’ 单引号 使用 \ 转义,避免SQL注入 )。
实例:使用PreparedStatement 执行查询
public static void load(int id) {
Connection conn = null;
PreparedStatement prst = null;
ResultSet rs = null;
try {
// 1 加载驱动
Class.forName("com.mysql.jdbc.Driver");
// 2 创建数据库连接对象
conn = DriverManager.getConnection(
"jdbc:mysql://127.0.0.1:3306/da", "root", "root");
// 这里我们用? 问号代替值,可以叫占位符,也可以叫通配符
String sql = "select * from test_jdbc where id = ?";
// 3 语句传输对象
prst = conn.prepareStatement(sql);
// 设置第一个?的值
prst.setInt(1, id);
rs = prst.executeQuery();
while (rs.next()) {
System.out.print(rs.getInt("id") + " ");
System.out.print(rs.getString("name") + " ");
System.out.println(rs.getString("money") + " ");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// 关闭资源,从上到下依次关闭,后打开的先关闭
if (rs != null) {
rs.close();
}
if (prst != null) {
prst.close();
}
if (conn != null) {
conn.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
以上的代码我们每个方法中都会部分重复一次,这是没必要的,因为不同的方法其实只是具体执行的SQL语句的内容不同,对于获取连接与释放资源,对应的逻辑是相同的。我们完全可以把这一段逻辑抽取出来,形成独立的类与方法,再在实际应用时调用对应的类和方法就可以了。
创建链接这些可以这样进行优化
public static Connection getConnection() throws ClassNotFoundException,
SQLException {
String username = "root";
String password = "root";
String url = "jdbc:mysql://127.0.0.1:3306/da";
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(url, username,
password);
return connection;
}
关闭资源这些可以这样进行优化
因为Connection和Statement/PreparedStatement以及ResultSet都实现了AutoCloseable接口
所以我们可以直接写AutoCloseable
public static void close(AutoCloseable obj) {
if (obj != null) {
try {
obj.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}