初学JDBC__第四节(SQL注入,PreparedStatement和Statement )

来源:互联网 发布:java教学 编辑:程序博客网 时间:2024/05/22 01:55

        SQL注入,PreparedStatement和Statement

1、在SQL中包含特殊字符或SQL的关键字(如:' or 1 or ')时Statement将出现不可预料的结果(出现异常或查询的结果不正确),可用PreparedStatement来解决。
2、PreperedStatement(从Statement扩展而来)相对Statement的优点:
             1.没有SQL注入的问题。
             2.Statement会使数据库频繁编译SQL,可能造成数据库缓冲区溢出。
             3.数据库和驱动可以对PreperedStatement进行优化(只有在相关联的数据库连接没有关闭的情况下有效)。
 
 
本节以增删查改中查询为例测试SQL注入
import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;public class sqlInject {/** * @param args * @throws SQLException  */public static void main(String[] args) throws SQLException {// TODO Auto-generated method stubread("rrrttt");}static void read(String name) throws SQLException{Connection conn=null;PreparedStatement ps=null;ResultSet rs=null;try{conn=jdbcUtils.getConnection();String sql="select id ,name,birthday,money from T_Users where name=?";ps=conn.prepareStatement(sql);ps.setString(1, name);rs=ps.executeQuery();while(rs.next()){System.out.println(rs.getObject("name")+"   "+rs.getObject("money"));}}finally{jdbcUtils.free(conn, ps, rs);}}}

原创粉丝点击