今天遇到一个浪费一个小时的坑。
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 无语。。。。。
另外既然都写了,
- PreparedStatement Statement的区别
public interface PreparedStatement extends Statement
- PreparedStatement 代码比Statement 可读性和可维护性。
- 预编译提高性能
- 防止sql注入
( 不要用 *,这样提高速度和性能)
F