版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_40788630/article/details/83239081
PreparedStatement对象可以对SQL语句进行预编译,预编译的信息会存储在PraparedStatement对象中。当相同的sql语句再次执行时,程序就会使用preparedstatement对象中的语句,
在web-chapter09项目中cn.itheima.jdbc包中创建一个名为Example02的的类,在该类中使用PreparedStatement对象对数据库进行插入数据的操作;
代码如下:
package cn.itheima.jdbc.example;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class example02 {
public static void main(String[] args) throws SQLException{
Connection conn = null;
PreparedStatement prestmt = null;
try {
//加载数据库驱动
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/jdbc";
String username = "root";
String password = "itcast";
//创建应用程序与数据库连接的connection对象
conn = DriverManager.getConnection(url, username, password);
//执行的SQL语句
String sql = "insert into users(name,password,email,birthday) values(?,?,?,?)";
//创建用来执行SQL语句的PreparedStatement对象
prestmt = conn.prepareStatement(sql);
prestmt.setString(1, "zzz");
prestmt.setString(2, "123456");
prestmt.setString(3, "[email protected]");
prestmt.setString(4, "1798-05-06");
//执行SQL
prestmt.executeUpdate();
}catch (ClassNotFoundException e) {
e.printStackTrace();
}finally {
//回收数据库资源
if(prestmt!=null) {
try {
prestmt.close();
}catch (Exception e) {
e.printStackTrace();
}
prestmt=null;
}
if(conn!=null) {
try {
conn.close();
}catch (Exception e) {
e.printStackTrace();
}
conn=null;
}
}
}
}
再来查看一下数据库