jdbc预编译可以有两种方式:
方式一、jdbc自己实现的预编译,就是做一下特殊字符处理来防SQL注入,看PreparedStatement源码就可以了。
public static void main(String[] args) {
try {
final String driverClassName = "com.mysql.jdbc.Driver";
final String url = "jdbc:mysql://10.6.9.14:3306/SBLOG"; 重点看这里
final String username = "sdl";
final String password = "sdl";
Connection connection = DriverManager.getConnection(url2, username, password);
String sql = " SELECT * " +
" FROM t_web " +
" WHERE id = ? and name like ?";
Class.forName(driverClassName);
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1, 1);
preparedStatement.setString(2, "%ing%");
ResultSet rst = preparedStatement.executeQuery();
rst.next();
System.out.println(rst.getString(2));
} catch (Exception e) {
e.printStackTrace();
}
}
这里是调用MySQL时的wireshark截图。可以看下实际上就是拼接完成的SQL发过去的。
方式二、利用MySQL的预编译,。
public static void main(String[] args) {
try {
final String driverClassName = "com.mysql.jdbc.Driver";
final String url2 = "jdbc:mysql://10.6.8.4:3306/SBLOG?useServerPrepStmts=true"; 重点看这里增加了useServerPrepStmts=true
final String username = "sdl";
final String password = "sdl";
Connection connection = DriverManager.getConnection(url2, username, password);
String sql = " SELECT * " +
" FROM t_web " +
" WHERE id = ? and name like ?";
Class.forName(driverClassName);
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1, 1);
preparedStatement.setString(2, "%ing%");
ResultSet rst = preparedStatement.executeQuery();
rst.next();
System.out.println(rst.getString(2));
} catch (Exception e) {
e.printStackTrace();
}
}
这里是调用MySQL时的wireshark截图。可以看下实际上参数是用的占位符?。
mybatis这种框架也是一样。关键看你的jdbc url怎么配置的,和框架没关系。