首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

怎么防止SQL语句注入

2012-10-06 
如何防止SQL语句注入版权:JavaIT学习室_在线Java学习论坛转载请标明,http://www.javait.org为了给大家将SQ

如何防止SQL语句注入
版权:JavaIT学习室_在线Java学习论坛
转载请标明,http://www.javait.org

为了给大家将SQL注入的原理,需要大家具备如下的知识:
(1)掌握基本Swing组件的开发
(2)掌握基本JDBC的开发

此课题的视频我们也为大家做好了。在文章的底部,大家可以看看。详细的SQL注入原理可以参考我们论坛的文章:http://forum.javait.org/viewthread.php?tid=53&extra=page%3D1

1、什么样的SQL语句是SQL注入语句

大家先看如下没有加入SQL注入设计的SQL语句

package test;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;/** * 数据库连接的类,利用JDBC技术完成 * @author JavaIT学习室 * */public class DBUtil {private static final String USER_NAME = "sa";private static final String PASSWORD = "123456";private static final String driverclass = "com.microsoft.sqlserver.jdbc.SQLServerDriver";private static final String url = "jdbc:sqlserver://localhost:1433;DatabaseName=stu";private static DBUtil db = null; //它是一个单例的对象private DBUtil() {try {Class.forName(driverclass); //加载驱动,必须将数据库的驱动包导入到工程中,不然会报错。sqljdbc.jar} catch (Exception e) {e.printStackTrace();}}/** * 返回主类DBConnectionUtil的对象,因为构造方法被定义为private,所以在初始化主类对象的时候只能用此方法实现 * @return */public static DBUtil getInstance() {if (db == null) {db = new DBUtil();}return db;}/** * 获取数据库连接Connection的对象 * @return */public Connection getConnection() {Connection conn = null;try {conn = DriverManager.getConnection(url, USER_NAME, PASSWORD);} catch (SQLException e) {e.printStackTrace();}return conn;}/** * 关闭数据库连接对象的方法 * @param conn */public void close(Connection conn) {try {conn.close();} catch (SQLException e) {e.printStackTrace();}}/** * 没有防止SQL注入的代码 * @return * @throws SQLException  */public int check(String sno) throws SQLException {String sql = "select count(sno) from student where sno = '"+sno+"'";System.out.println(sql);Statement stmt = DBUtil.getInstance().getConnection().createStatement();ResultSet rs = stmt.executeQuery(sql);if (rs != null && rs.next()) { //对执行的SQL语句的结果集进行遍历if (rs.getInt(1) > 0) {return 1; //确认该学生在数据库中存在}}return 0;}/** * PreparedStatement可以防止SQL注意的接口 * @param sno * @return * @throws SQLException */public int check_2(String sno) throws SQLException {String sql = "select count(sno) from student where sno = ?";PreparedStatement ps = DBUtil.getInstance().getConnection().prepareStatement(sql);ps.setString(1, sno);ResultSet rs = ps.executeQuery();if (rs != null && rs.next()) { //对执行的SQL语句的结果集进行遍历if (rs.getInt(1) > 0) {return 1; //确认该学生在数据库中存在}}return 0;}}

热点排行
Bad Request.