java中对数据库访问的方法有多种。以操作MySql数据库为例。
方法一:创建Statement对象,调用对象的execute(String)、executeQuery(String)等函数执行String字符串的sql语句。
Class.forName(com.mysql.jdbc.Driver); //加载驱动
Connection con = DriverManager.getConnection("jdbc:mysql://...."); //创建与mysql中某个数据库的连接
Statement st = con.CreateStatement(); //创建一个Statement对象
String id = "03"; //
String sq = "delete from table1 where id="+id; //构建sql语句
st.execute(sq); //执行sql语句
上面这段代码的本意是要删除id=03的记录,但是如果有人将id的内容改为“03 or 1=1”。那么表中的任何记录都将被删除,后果十分严重。
这是Statement的一大缺点:不能防止sql注入。
另一个缺点是,每次执行都需要重新编译sql语句,效率低下。而PreparedStatement则解决了这些问题。
方法二:创建PreparedStatement对象
Class.forName(com.mysql.jdbc.Driver); //加载驱动
Connection con = DriverManager.getConnection("jdbc:mysql://...."); //创建与mysql中某个数据库的连接
String sq = "delete from table1 where id=? and name=?"//构建sql语句,以?作为占位符,这个位置的值待设置
PreparedStatement ps = con.prepareStatement(sq); //创建PreparedStatement时就传入sql语句,实现了预编译
ps.setString(1,"03");
ps.setString(2,"mao"); //设置sql语句的占位符的值,注意第一个参数位置是1不是0
ps.execute(); //执行这个PreparedStatement
//设置占位符的值还可以通过setObject(int,object)完成
//上面代码的作用时删除表中id=03且name=mao的记录
为什么PreparedStatement能防止sql注入呢?
因为sql语句是预编译的,而且语句中使用了占位符,规定了sql语句的结构。用户可以设置"?"的值,但是不能改变sql语句的结构,因此想在sql语句后面加上如“or 1=1”实现sql注入是行不通的。
实际开发中,一般采用PreparedStatement访问数据库,它不仅能防止sql注入,还是预编译的(不用改变一次参数就要重新编译整个sql语句,效率高),此外,它执行查询语句得到的结果集是离线的,连接关闭后,仍然可以访问结果集。