SQL注入与防范

博客提出SQL语句由动态拼接而成时,用户输入加入命令可能改变SQL语意的问题,并给出解决方案,即使用Connection.preparedStatement(sql)实现占位符来防范风险。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SQL语句由动态拼接而成,用户输入加入命令可能会导致SQL语意改变,如何防范?

解决方案 Connection

.preparedStatement(sql) (实现占位符)

PreparedStatement
.setInt
.setString
.setBoolean
import java.sql.Statement;

public class HelloJDBC{
	//数据库驱动
	static final String JDBC_DRIVER = "";
	static final String DB_URL ="";
	static final String USER ="";
	static final String PASSWORD ="";

	public static void helloword() throws ClassNotFoundException(){
		Connection conn = null;
		PreparedStatement ptmt = null;
		ResultSet rs = null;

		//1.装载驱动程序
		Class.forName(JDBC_DRIVER);
		//2.建立数据库连接
		try{
			conn = DriverManager.getConnerction(DB_URL,USER,PASSWORD);
			//3.执行SQL语句
			ptmt = conn.prepareStatement("select * from user where userName = ? and password = ?");
			ptmt.setString(1,userName);
			ptmt.setString(2,password);
			rs = ptmt.excuteQuery();
			//4.获取执行结果
			while(rs.next()){
				user = new User();
				user.setUserName(rs.getString("userName"));
				user.setSex(rs.getBoolean("sex"));
			}
		}catch (SQLException e){
			e.printStackTrace();
		}finally(){
		//5.清理环境
		try{
				if(conn != null)
					conn.close();	
				if(ptmt != null)
					ptmt.close()
				if(rs != null)
					rs.close()
				}catch(SQLException e){
					//ignore
				}
			}
			return user;
		}
	}
}

|

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值