import java.sql.Connection;
import java.sql.PreparedStatement; //注意:导入的是java.sql里的PrearedStatement
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class SQLInject {
public static void main(String[] args) throws SQLException {
read("JiangLR");
}
public static void read(String name) throws SQLException {
Connection conn = null;
PreparedStatement ps = null;
/*
* 对查询语句进行提前预处理检查,防止Statement的SQL注入,而且效率比Statement高
* 同样对增删改操作建议使用PrepareStament来构造对象
* */
ResultSet rs = null;
try {
// 2.建立连接
conn = jdbcUtils.getinstance().getConnection();
// 3.创建执行SQL的语句
/*
* String sql = "select id, name, birthday, money from user where name = '" + name + "'";
* 因为上面的语句不安全,所以替换成了下面的SQL语句(把特殊字符过滤掉)
* */
String sql = "select id, name, birthday, money from user where name = ?";
ps = conn.prepareStatement(sql);
ps.setString(1, name);
/*
* 第一个参数表示替换第几个'?',因为一个SQL语句里可能有多个问号
* 第二个参数表示用什么来替换?比如上面用方法传进来的name参数替换'?'
* */
// 4.执行语句
rs = ps.executeQuery();//此时不需要参数,因为查询语句已经提前给了
// 5.处理结果
while (rs.next()) { // 推荐写列名,不建议写索引号
System.out.println("id:" + rs.getObject("id") + '\t' + rs.getObject("name") + '\t'
+ rs.getObject("birthday") + '\t' + rs.getObject("money"));
}
} finally {
// 6.释放资源
jdbcUtils.free(rs, ps, conn); //因为ps是Statement的子类,所以不会报错
}
}