之前在JdbcBase这个系列里我们学习到了Statement这个类来获得连接对象 但是这个类我们在前言里面说到有一些缺点 现在我们就要学习一下比这类好用的另一个相似的类PreparedStatement
声明:—— Stu类依旧是我在终端创建的表和相对应的实体类 jdbc是之前创建的数据库 之后的系列也会用到就不一一讲了 这里先声明一下 以免小伙伴不知道我的stu 和jdbc是怎么回事—–
首先 创建一个JdbcPrepare类
//PreparedStatement:
//1, 可以防止SQL注入
//2, 采取的是预编译的操作,将sql语句先交给数据库编译,
// 只需要等待执行就可以了,当多个重复语句被执行时效率会比Statement高,速度快
@Test
public void t1() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc", "root", "111111");
//之前的写法
// Statement statement = connection.createStatement();
//现在的写法
//?就是一个占位符
//占位符 :就是先占住一个固定的位置,等着你再往里面添加内容的符号
PreparedStatement pstmt = connection.prepareStatement("INSERT INTO stu VALUES (NULL , ?, ?);");
//第一个参数是?的位置
//与values后面括号中是否有null,是否有具体的值无关
// 在sql语句中有几个问号,
// 那么就需要向sql中传递几个参数
// 第几个问号,
// 那么下面方法中的第一个参数就填几
pstmt.setString(1, "张三");
pstmt.setInt(2, 40);
pstmt.executeUpdate();
}
@Test
public void t2Update() throws SQLException {
Connection connection = JdbcUtil.getConnection();
String update = "update stu set name=? where id=?;";
//获得预处理对象
PreparedStatement pstm = connection.prepareStatement(update);
//将参数传到sql语句中
pstm.setString(1, "大华");
//查找id为7的数据,将该条数据的name字段改为大华
pstm.setInt(2, 7);
//执行语句
pstm.executeUpdate();
}
@Test
public void t3Query() throws SQLException {
Connection connection = JdbcUtil.getConnection();
PreparedStatement pstm = connection.prepareStatement("SELECT *FROM stu WHERE name=?;");
pstm.setString(1, "大华");
ResultSet resultSet = pstm.executeQuery();
while (resultSet.next()) {
System.out.println("找到了:id 为" + resultSet.getInt(1) + "\t" + " name: " + resultSet.getString(2));
// System.out.println(resultSet.getString("name") + resultSet.getInt("age"));
}
}
@Test
public void t4Delete() throws SQLException {
Connection connection = JdbcUtil.getConnection();
PreparedStatement pstm = connection.prepareStatement("DELETE FROM stu WHERE name=?;");
pstm.setString(1, "张三");
int i = pstm.executeUpdate();
System.out.println("删除了名字为张三的值: " + i);
}
}