原视频地址:https://www.bilibili.com/video/av67955358?p=17
使用Statement操作数据表的弊端:
1.存在拼串操作,比较繁琐
2.存在SQL注入问题
PreparedStatement是Statement的子接口
先将资源关闭与获取的方式封装到一个类中:
package day1; import java.io.InputStream; import java.sql.Connection; import java.sql.Driver; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; import org.junit.jupiter.api.Test; public class JUnittext { @Test public void connectiontest1() throws SQLException { Driver driver = new com.mysql.jdbc.Driver(); String url = "jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2B8"; Properties info = new Properties(); info.setProperty("user", "root"); info.setProperty("password", "sqw991017"); Connection conn = driver.connect(url, info); System.out.println(conn); } @Test public void connectiontest2() throws Exception { Class clazz = Class.forName("com.mysql.jdbc.Driver"); Driver driver = (Driver) clazz.getDeclaredConstructor().newInstance(); String url = "jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2B8"; Properties info = new Properties(); info.setProperty("user", "root"); info.setProperty("password", "sqw991017"); Connection conn = driver.connect(url, info); System.out.println(conn); } @Test public void connectiontest3() throws Exception { /* * Class clazz = Class.forName("com.mysql.jdbc.Driver"); Driver driver = * (Driver) clazz.getDeclaredConstructor().newInstance(); //注册驱动 * DriverManager.registerDriver(driver); */ String url = "jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2B8"; String user = "root"; String password = "sqw991017"; Connection conn = DriverManager.getConnection(url, user, password); System.out.println(conn); } @Test public void connectiontest4() throws Exception { //读取配置文件的4个基本信息 InputStream is = JUnittext.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 conn = DriverManager.getConnection(url, user, password); System.out.println(conn); } }
通用的增删改操作:
//1.获取链接
//2.预编译sql语句
//3.填充占位符
//4.执行
//5.关闭资源
@Test public void testcommonupdatetest() { //Object test1 = new Object[]{3}; String sql="delete from customers where id = ?"; Update(sql,3); } //通用的增删改操作 public void Update(String sql,Object ...args) { //1.获取链接 Connection conn = null; PreparedStatement ps = null; try { conn = JDBCutils.getConnection(); //2.预编译sql语句 ps = conn.prepareStatement(sql); //3.填充占位符 for(int i=0;i<args.length;i++) { ps.setObject(i+1, args[i]); } //4.执行 ps.execute(); } catch (Exception e) { e.printStackTrace(); }finally { //5.关闭资源 JDBCutils.closeResource(conn, ps); } }