PreparedStatement 坑:)

今天遇到一个浪费一个小时的坑。

public static void main(String[] args) {
        String sql = "insert into stu(sno,name,dept,sex,phone,password,age) values(?,?,?,?,?,?,?)";
        ConnectJDBC connectJDBC = new ConnectJDBC();
        Connection connection = connectJDBC.con;
        try {
            PreparedStatement ps = connection.prepareStatement(sql);
            ps.setString(1,"1");
            ps.setString(2,"s");
            ps.setString(3,"s");
            ps.setBoolean(4,true);
            ps.setString(5,"s");
            ps.setString(6,"z");
            ps.setInt(7,9);
            System.out.println(ps.toString());
            ps.executeUpdate(sql);
            System.out.println(ps.toString());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

com.mysql.cj.jdbc.ClientPreparedStatement: insert into stu(sno,name,dept,sex,phone,password,age) values(‘1’,‘s’,‘s’,1,‘s’,‘z’,9)
结果报错 for the right syntax to use near ‘?,?,?,?,?,?,?)’
我本以为是sql 有错又查了网上,ps.toString() 打印的去mysql运行是可以的,捣鼓捣鼓一个小时后,灵光一闪发现了问题

PreparedStatement ps = connection.prepareStatement(sql);
ps.executeUpdate(sql);

两个sql 无语。。。。。
另外既然都写了,

  1. PreparedStatement Statement的区别
public interface PreparedStatement extends Statement
  1. PreparedStatement 代码比Statement 可读性和可维护性。
  2. 预编译提高性能
  3. 防止sql注入
    ( 不要用 *,这样提高速度和性能)

F

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值