使用PreparedStatement实现CRUD操作
/*
PreparedStatement vs Statement
1.PreparedStatement是Statement的子类;
2.PreparedStatement 能最大可能提高性能:
2.1.DBServer会对预编译语句提供性能优化。因为预编译语句有可能被重复调用,所以语句在被DBServer的编译器编译后的执行代码被缓存下来,那么下次调用时只要是相同的预编译语句就不需要编译,只要将参数直接传入编译过的语句执行代码中就会得到执行。
2.2.在statement语句中,即使是相同操作但因为数据内容不一样,所以整个语句本身不能匹配,没有缓存语句的意义.事实是没有数据库会对普通语句编译后的执行代码缓存。这样每执行一次都要对传入的语句编译一次。
2.3(语法检查,语义检查,翻译成二进制命令,缓存)
3.PreparedStatement 可以防止 SQL 注入
*/
预备:首先将连接操作和异常处理封装到JDBCUtils类中:
public static Connection getConnection() throws Exception{
//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 conn = DriverManager.getConnection(url, user, password);
return conn;
}
// 关闭连接和Statement、ResultSet操作
public static void closeResource(Connection conn, Statement ps, ResultSet rs){
try {
if(ps != null)
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if(conn != null)
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if(rs != null)
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 关闭连接和Statement、ResultSet操作
public static void closeResource(Connection conn, Statement ps, ResultSet rs){
try {
if(ps != null)
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if(conn != null)
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if(rs != null)
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
一、PreparedStatement实现增删改操作(没有返回值)
/*
- 使用PreparedStatement来替换Statement,实现对数据表的增删改操作
- 增删改:无返回
- 查:有返回
*/
@Test
public void test1() throws Exception{
String sql1 = "insert into customers(name,email,birth) values(?,?,?)";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf.parse("2020-03-05");
// testGeneralMethod(sql1, "张三", "73640@qq.com", new java.sql.Date(date.getTime()));
String sql2 = "delete from customers where id = ?";
// testGeneralMethod(sql2, 20);
String sql3 = "update `order` set order_name = ? where order_id = ?";
testGeneralMethod(sql3, "DD", 2);
}
//通用的增删改方法
public void testGeneralMethod(String sql, Object...args){ //sql中占位符的个数与可变形参的个数相同
Connection conn = null;
PreparedStatement ps = null;
try {
//1.获取数据库的连接
conn = JDBCUtils.getConnection();
//2.预编译sql语句,返回PreparedStatement的实例
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);
}
}
//修改customers表的一条记录
@Test
public void testUpdate(){
Connection conn = null;
PreparedStatement ps = null;
try {
//1.获取数据库的连接
conn = JDBCUtils.getConnection();
//2.预编译sql语句,返回PreparedStatement实例
String sql = "update customers set name = ? where id = ?";
ps = conn.prepareStatement(sql);
//3.填充占位符
ps.setObject(1, "莫扎特");
ps.setObject(2, 18);
//4.执行
ps.execute();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
//5.关闭资源
JDBCUtils.closeResource(conn, ps);
}
}
//向customers表中添加一条记录
@Test
public void testInsert(){
Connection conn = 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.获取连接
conn = DriverManager.getConnection(url, user, password);
System.out.println(conn);
//4.预编译sql语句,返回PreparedStatement实例
String sql = "insert into customers(name,email,birth) values(?,?,?)"; //?:占位符
ps = conn.prepareStatement(sql);
//5.填充占位符
ps.setString(1, "哪吒");
ps.setString(2, "nezha@gmail.com");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date date = sdf.parse("1000-01-01");
ps.setDate(3,new java.sql.Date(date.getTime()));
//6.执行sql操作
ps.execute();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
//7.资源的关闭
try {
if(ps != null)
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if(conn != null)
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
二、查询操作(有返回值)
/**
*
- @Description 使用PreparedStatement实现针对于不同表的通用的查询操作
- @author baiyexing
- @version
- @date2020年12月3日下午7:55:13
*/
@Test
public void testGetForList(){
String sql = "select id,name,email from customers where id < ?";
List<Customer> list = getForList(Customer.class, sql, 12);
Iterator<Customer> iterator = list.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
//或者用方法引用
//list.forEach(System.out::println);
}
public <T> List<T> getForList(Class<T> clazz, String sql, Object...args){
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = JDBCUtils.getConnection();
ps = conn.prepareStatement(sql);
//填充占位符
for(int i=0 ; i < args.length ; i++){
ps.setObject(i+1, args[i]);
}
rs = ps.executeQuery();
//获取结果集的元数据:ResultSetMetaData
ResultSetMetaData rsmd = rs.getMetaData();
//通过ResultSetMetaData获取结果集中的列数
int columnCount = rsmd.getColumnCount();
//创建集合对象
ArrayList<T> list = new ArrayList<T>();
while(rs.next()){
T t = clazz.newInstance();
// 处理结果集一行数据中的每一个列: 给t对象指定的属性赋值
for(int i = 0; i < columnCount ; i++){
//获取列值
Object columnValue = rs.getObject(i + 1);
//获取每个列的别名,如果没有就是列名
String columnLabel = rsmd.getColumnLabel(i + 1);
//给t对象指定的某个属性,赋值为columnValue:通过反射
Field field = t.getClass().getDeclaredField(columnLabel);
//或者
//Field field = clazz.getDeclaredField(columnLabel);
field.setAccessible(true);
field.set(t, columnValue);
}
list.add(t);
}
return list;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
JDBCUtils.closeResource(conn, ps, rs);
}
return null;
}
三、 ResultSet与ResultSetMetaData
3.4.1 ResultSet
- 查询需要调用PreparedStatement 的 executeQuery() 方法,查询结果是一个ResultSet 对象
- ResultSet 对象以逻辑表格的形式封装了执行数据库操作的结果集,ResultSet 接口由数据库厂商提供实现
- ResultSet 返回的实际上就是一张数据表。有一个指针指向数据表的第一条记录的前面。
- ResultSet 对象维护了一个指向当前数据行的游标,初始的时候,游标在第一行之前,可以通过 ResultSet 对象的next()方法移动到下一行。调用 next()方法检测下一行是否有效。若有效,该方法返回 true,且指针下移。相当于Iterator对象的hasNext() 和 next() 方法的结合体。
- 当指针指向一行时, 可以通过调用 getXxx(int index) 或 getXxx(int columnName) 获取每一列的值。
例如: getInt(1), getString(“name”) 注意:Java与数据库交互涉及到的相关Java API中的索引都从1开始。