PreparedStatement是statement的子接口,通过statement对象执行SQL语句时,需要将SQL语句发送给DBMS,由DBMS首先进行编译后再执行,预编译语句和Statement不同,再创建PrepareStatedment对象时就指定了SQL语句,该语句立即发送DBMS进行编译,当编译语句被执行时,DBMS直接运行编译后的SQL语句,而不需要像其他的SQL语句那样,需要先进行编译
什么时候使用预编译语句:
一般是在需要反复使用一个SQL语句时才使用预编译语句,通过反复设置参数从而多次使用该SQL语句,为了防止SQL注入漏洞,在某些数据操作中也是用预编译语句
JDBC使用预编译的好处:
1.执行效率
2.代码的可读性,可维护性
3.SQL执行的安全性
4.减少硬解析,节约大量的CPU资源
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.Properties;
public class PreparedStatement {
public static void main(String[] args) throws Exception {
Properties properties = new Properties();
properties.load(new FileInputStream("src\\mysql.properties"));
//获取相关的值
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String driver = properties.getProperty("driver");
String url = properties.getProperty("url");
//1.加载驱动
Class.forName(driver);//加载驱动
//2.得到连接
Connection connection = DriverManager.getConnection(url, user, password);
//3.得到PreparedStatement
//3.1组织一个sql ?相当于占位符
//查询
String sql = "select name,pwd from admine where name =? and pwd = ?";
//3.2preparedstatement对象实现了PreparedStatement接口的实现类的对象
java.sql.PreparedStatement preparedStatement = connection.prepareStatement(sql);
//3.3给?赋值
preparedStatement.setString(1,admin_name);
preparedStatement.setString(2,admin_pwd);
//执行select语句需要使用executeQuery
//如果执行dml(update,insert,delete)就要使用executeUpdate()
//这里执行executeQuery 不要写sql
ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
System.out.println("恭喜 登陆成功");
} else {
System.out.println("对不起 登陆失败");
}
resultSet.close();
preparedStatement.close();
connection.close();
}
}