package jdbc;
import java.sql.*;
public class PreparedStatementDemo {
public static void main(String[] args) throws SQLException{
// 在test1中,SQL语句的执行是通过Statement对象实现的。Statement对象每次执行SQL语句时,都会对其进行编译。当相同的SQL语句执行多次时,Statement对象就会使数据库频繁编译相同的SQL语句,从而降低数据库的访问效率
// 为了解决上述问题,Statement提供了一个子类PreparedStatement,PreparedStatement对象可以对SQL语句进行预编译,预编译的信息会存储在PreparedStatement对象中
PreparedStatement pstmt = null;//创建PreparedStatement对象
Connection conn = null;
try {
// 注册数据库驱动
Class.forName("com.mysql.jdbc.Driver");
// 2.通过DriverManager获取数据库连接
String url = "jdbc:mysql://localhost:3306/jdbc?useSSL = false";
String username = "root";
String password = "root";
conn = DriverManager.getConnection(url, username, password);
// 3.使用Statement执行SQL语句
String sql = "insert into users(name,password,email,birthday)"+"values(?,?,?,?)";
// 4.创建执行SQL语句的prepareStatement对象
pstmt = conn.prepareStatement(sql);
// 5.为SQL与语句中参数赋值,即value的值name,password,email,birthday,因为id有auto_increse所以可以不写
pstmt.setString(1, "ZL");
pstmt.setString(2, "123456");
pstmt.setString(3, "ZL@sina.com");
pstmt.setString(4, "1789-12-23");
// 6.执行SQL
pstmt.executeUpdate();
}catch(Exception e) {
e.printStackTrace();
}finally {
// 7.回收数据库资源
if(pstmt != null) {
try {
pstmt.close();
}catch(SQLException e) {
e.printStackTrace();
}
pstmt = null;
}
if(conn != null) {
try {
conn.close();
}catch(SQLException e) {
e.printStackTrace();
}
conn = null;
}
}
}
}