一、PreparedStatement的介绍
PreparedStatement用来执行一段SQL语句,返回查询的结果集或更新影响的行数。
执行的SQL语句中的参数使用 ? 代替,通过setString、setInt等方法,按顺序对?代表的参数赋值
二、PreparedStatement的好处
1. 简化了SQL语句的编写,不再需用使用字符串拼接出SQL语句。
2. 防止SQL注入问题的发生
3. 减少编译次数,提升效率
三、使用案例
package jdbc;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;
public class pre_test {
public static void main(String[] args) throws Exception{
// 1.读取配置文件
Properties properties = new Properties();
properties.load(new FileInputStream("src/jdbc/mysql.properties"));
// 2.注册驱动 获取连接
String url = properties.getProperty("url");
Connection connection = DriverManager.getConnection(url, properties);
// 3.获取PreparedStatement 准备SQL语句
String sql = "select * from admin where name = ?";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
// 3.1 设置参数的值
preparedStatement.setString(1, "admin");
// 4.执行SQL语句
// 查询用 executeQuery() 更新用 executeUpdate()
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
// 这里可以使用查询到的字段名 或者 索引值(从1开始)
String name = resultSet.getString(1);
String passwd = resultSet.getString("passwd");
System.out.println(name + ":" + passwd);
}
// 5.关闭连接
resultSet.close();
preparedStatement.close();
connection.close();
}
}