SQL注入,PreparedStatement和Statement

SQL中包含特殊字符或SQL的关键字(如:' or 1 or ')Statement将出现不可预料的结果(出现异常或查询的结果不正确),可用PreparedStatement来解决。

PreperedStatement(从Statement扩展而来)相对Statement的优点:

       1.没有SQL注入的问题。

       2.Statement会使数据库频繁编译SQL,可能造成数据库缓冲区溢出。

       3.数据库和驱动可以对PreperedStatement进行优化(只有在相关联的数据库连接没有关

闭的情况下有效)。

 

public void read(String name) throws SQLException {

              Connection conn = null;

              PreparedStatement ps = null;

              ResultSet rs = null;

              try {

                     // 2.建立连接

                     conn = JdbcUtils.getConnection();

 

                     // conn = JdbcUtilsSing.getInstance().getConnection();

                     // 3.创建语句

                     String sql = "select id, name, money, birthday  from user where name=?";

                     ps = conn.prepareStatement(sql);

                     ps.setString(1, name);

                     // 4.执行语句

                     rs = ps.executeQuery();

 

                     // 5.处理结果

                     while (rs.next()) {

                            System.out.println(rs.getInt("id") + "\t"

                                          + rs.getString("name") + "\t" + rs.getDate("birthday")

                                          + "\t" + rs.getFloat("money"));

                     }

 

              } finally {

                     JdbcUtils.free(rs, ps, conn);

              }

       }

 

       public void read1(String name) throws SQLException {

              Connection conn = null;

              Statement st = null;

              ResultSet rs = null;

              try {

                     // 2.建立连接

                     conn = JdbcUtils.getConnection();

                     // conn = JdbcUtilsSing.getInstance().getConnection();

 

                     // 3.创建语句

                     String sql = "select id, name, money, birthday  from user where name='"

                                   + name + "'";

                     st = conn.createStatement();

                     // 4.执行语句

                     rs = st.executeQuery(sql);

 

                     // 5.处理结果

                     while (rs.next()) {

                            // System.out.println(rs.getObject("id") + "\t"

                            // + rs.getObject("name") + "\t"

                            // + rs.getObject("birthday") + "\t"

                            // + rs.getObject("money"));

                     }

              } finally {

                     JdbcUtils.free(rs, st, conn);

              }

       }

对于read1()方法,若传入的name' or 1 or '则会把数据库里所有记录都查询出来。而read()用的PerparedStatement就不会出显这种情况。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值