MySQL PreparedStatement 方法
创建PreparedStatement对象
PreparedStatement preparedStatement = connection.PreparedStatement(sql语句);
此时sql语句必须写好,不能通过一个变量再进行传入,因为PreparedStatement要做预编译
PreparedStatement preparedStatement = connection.prepareStatement("select * from lesson where lessonname = ? and lessonteacher = ?"); preparedStatement.setString(1,"数据结构"); preparedStatement.setString(2,"刘丹"); System.out.println(preparedStatement);
当PreparedStatement preparedStatement = connection.prepareStatement("select * from lesson where lessonname = ? and lessonteacher = ?");的括号中有内容时,后面再调用executeUpdate()或者executeQuery()的括号中的语句默认为preparedStatement()括号中的内容。
PreparedStatement preparedStatement = connection.prepareStatement("select * from lesson where lessonname = ? and lessonteacher = ?"); preparedStatement.setString(1,"数据结构"); preparedStatement.setString(2,"刘丹"); ResultSet resultSet = preparedStatement.executeQuery(); if(resultSet.next()) { System.out.println("查找成功"); }