PreparedStatement
获取数据库连接
//方式五:将数据库连接需要的4个基本信息声明在配置文件中,通过读取配置文件的方式,获取连接
@Test
public void getConnection5() throws Exception {
//1. 读取配置文件的4个基本信息
InputStream is = ConnectionTest.class.getClassLoader().getResourceAsStream("jdbc.properties");
Properties pros = new Properties();
pros.load(is);
String user = pros.getProperty("user");
String password = pros.getProperty("password");
String url = pros.getProperty("url");
String driverClass = pros.getProperty("driverClass");
//2. 加载驱动
Class.forName(driverClass);
//3. 获取连接
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println(connection);
}
配置文件在src的jdbc.properties
user=root
password=0930
url=jdbc:mysql://localhost:3306/test
driverClass=com.mysql.jdbc.Driver
PreparedStatement
- 当我们和数据库取得连接后,我们需要用在java中写sql语句 放到数据库中去执行,PreparedStatement 就相当于是一个信使的作用。
- PreparedStatement 是替代Statement,它是Statement的子接口,因为Statement有要拼接字符串 且有SQL注入问题。
PreparedStatement 和statement对比
用PreparedStatement实现数据库的增删改查操作
-
通用的步骤:
1. 获取数据库的连接 2. 预编译sql语句,返回PreparedStatement的实例 3. 填充占位符 4. 执行 5. 资源的关闭
添加操作
//向customers表中添加一条记录
@Test
public void testInsert() {
Connection connection = null;
PreparedStatement ps = null;
try {
//1. 读取配置文件的4个基本信息
InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");
Properties pros = new Properties();
pros.load(is);
String user = pros.getProperty("user");
String password = pros.getProperty("password");
String url = pros.getProperty("url");
String driverClass = pros.getProperty("driverClass");
//2. 加载驱动
Class.forName(driverClass);
//3. 获取连接
connection = DriverManager.getConnection(url, user, password);
System.out.println(connection);
//4. 预编译sql语句,返回PreparedStatement的实例
String sql = "insert into customers(name,email,birth)values(?,?,?)";
ps = connection.prepareStatement(sql);
//5.填充占位符
ps.setString(1,"哪咤");
ps.setString(2,"nazha@gmail.com");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf.parse("1000-01-01");
ps.setDate(3,new java.sql.Date(date.getTime()));
//6. 执行操作
ps