PrepareStatment:
1,可以防止SQL注入
2,采取预编译的方式,将SQL语句先交给数据库编译好
只需要等待执行就可以了,当多个重复语句被执行时效率会比Statement高,速度快
@Test//关于PrepareStament的增删改查
public void t1() throws SQLException, ClassNotFoundException {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc","root","newpass");
//?就是一个占位符
PreparedStatement pstmt = conn.prepareStatement("INSERT INTO stu VALUES (NULL,?,?);");
//第一个参数是?的位置
//有几个问号就传递几个参数
//第几个问号,角标就是几
pstmt.setString(1,"张三");
pstmt.setObject(2,40);
pstmt.executeUpdate();
PreparedStatement pstmt1 = conn.prepareStatement("UPDATE stu SET `name` =? WHERE id=?;");
//将参数传到SQL语句中
pstmt1.setObject(1,"刘振洲");
//查找id为1的数据,将该条数据的name字段改为刘振洲
pstmt1.setObject(2,2);
//执行语句
pstmt1.executeUpdate();
PreparedStatement pstmt2 = conn.prepareStatement("SELECT * FROM stu WHERE `name`=?;");
//将参数传到SQL语句中
pstmt.setObject(1,"刘振洲")