【07】PreparedStatement接口

博客介绍了PreparedStatement,它是java.sql包中继承自Statement接口、表示预编译SQL语句的对象。使用它可避免SQL注入攻击,这种攻击会用特定字符串绕过验证访问数据库。编写SQL语句时可用占位符代替变量,还介绍了为PreparedStatement对象设置参数的语法、示例及代码。

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

1. PreparedStatement

  • java.sql包
  • 继承自Statement接口
  • 表示预编译的 SQL 语句的对象。
  • 好处
    • 避免SQL注入攻击

2. SQL注入攻击

用特定格式的字符串,直接访问数据库,绕过用户名和密码的验证;

String stuName = "张三' or '1'='1";  //用户名,注入攻击字符串
int stuNo = 400;//密码
sql = "select stuNo,stuName,age,birthday,score
  from Student
    where stuName  = '"+stuName+"' and stuNo = "+stuNo;

3. 使用占位符?代替变量

编写SQL语句的时候,不需要关心拼接SQL语句的单引号和变量。

   String sql = "insert into Student(stuNo,stuName,age,birthday,score) 
   	values (seq_stu.nextval,?,?, to_date(?,'yyyy-MM-DD'),?)";

4. 为PreparedStatement对象设置参数

4.1 语法

    pstmt.setXXX(位置,值);

	注意:位置从1开始

4.2 示例

    pstmt.setString(1, stuName);
    pstmt.setInt(2, age);
    pstmt.setString(3, birthday);
    pstmt.setDouble(4, score);

4.3 示例代码

    PreparedStatement pstmt = null;
    //声明变量
    String stuName = "lisi";
    int age = 17;
    String birthday = "1987-1-11";
    double score = 89.35;
    //SQL语句
    String sql = "insert into Student(stuNo,stuName,age,birthday,score)
    	 values (seq_stu.nextval,?,?, to_date(?,'yyyy-MM-DD'),?)";
    //实例化pstmt,对SQL进行编译(预编译)
    pstmt = conn.prepareStatement(sql);
    //设置参数(占位符从1开始)
    pstmt.setString(1, stuName);
    pstmt.setInt(2, age);
    pstmt.setString(3, birthday);
    pstmt.setDouble(4, score);
    //执行SQL语句
    int i = pstmt.executeUpdate();
    System.out.println("影响行数:" + i);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值