利用 PreparedStatement 可以有效解决 Statement 带来的安全隐患问题
本文主要介绍 PreparedStatement 进行数据库增加数据的操作,利用的数据库如下

- import java.io.InputStream;
- import java.sql.DriverManager;
- import java.text.SimpleDateFormat;
- import java.util.Date;
- import java.util.Properties;
- import com.mysql.jdbc.Connection;
- import com.mysql.jdbc.PreparedStatement;
-
- public class PreparedStatementTest {
- public static void main(String[] args) throws Exception {
- //1.读取文件中的信息
- InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");
- //将用户名和密码封装在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 conn = (Connection) DriverManager.getConnection(url, user, password);
- //4.预编译sql语句,返回PrepareStatement的实例
- String sql = "insert into customers(name,email,birth)values(?,?,?)";
- PreparedStatement ps = (PreparedStatement) conn.prepareStatement(sql);
- //5.填充占位符
- ps.setString (1,"哪吒");
- ps.setString(2,"nezha@gmail.com");
- ps.setDate(3,(java.sql.Date) new java.sql.Date(3125346436315L));
- //6.执行操作
- ps.execute();
- //7.资源关闭
- ps.close();
- conn.close();
- }
- }
最后插入成功
