一.Statement和PreparedStatement区别分析总结
相同点:都是在java中提交sql语句给数据库的对象。
不同点:Statement向数据库一次提交sql语句和参数,PreparedStatement(预编译)先向数据库提交sql语句,后提交参数。
预编译:数据库提前编译好了sql语句,只需要传入参数就可以查询。输入的sql参数,它都会当作字符串去数据库中检索。
案例:采用mysql测试
package cs.jdbc;
import java.sql.*;
/**
* 测试jdbc
*
* @author cs
* @date 2018年5月28日
*/
public class TestJDBC {
// 获取查询返回结果
private ResultSet result;
/**
* 测试statment
* mybatis底层中 ${} 采用的就是此方式,所以存在sql注入,不建议使用
*/
public void testStatement() {
try {
// 正常的sql
String sql = "select * from tb_xs where name='cs' "; //结果 2
// sql注入,参数值为 ( ' or 1=1# )
// String sql = "select * from tb_xs where name='' or 1=1#' "; //结果 5(所有数据)
int rowCount = 0;
Statement statement = JDBCUtils.getStatement();
result = statement.executeQuery(sql);
while (result.next()) {
rowCount++;
}
System.out.println("总行数:"+rowCount);
} catch (SQLException e) {
e.printStackTrace();
} finally {
JDBCUtils.close();
}
}
/**
* 测试PreparedStatement(预编译)
* mybatis中底层 #{} 采用就是次此方式实现的,建议使用
*/
public void testPreparedStatement() {
try {
String sql = "select * from tb_xs where name=? ";
PreparedStatement preparedStatement = JDBCUtils.getPreparedStatement(sql);
//正常sql
preparedStatement.setString(1, "cs"); //结果 总行数:2
//sql注入
// preparedStatement.setString(1, "' or 1=1#'"); //结果 总行数:2
// 获取查询返回结果
result = preparedStatement.executeQuery();
int rowCount = 0;
while (result.next()) {
rowCount++;
}
System.out.println("总行数:"+rowCount);
} catch (SQLException e) {
e.printStackTrace();
} finally {
JDBCUtils.close();
}
}
public static void main(String[] args) {
// new TestJDBC().testStatement();
new TestJDBC().testPreparedStatement();
}
}
案例代码下载
https://download.csdn.net/download/cs4380/10443326