BaseDao的封装(更新操作和查询操作)

package com.liujinghe.util;

import org.apache.commons.beanutils.BeanUtils;

import java.lang.reflect.InvocationTargetException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class BaseDao6 {
//增删改
public int update(String sql,Object [] parameters) throws SQLException {
//获取数据库链接对象
Connection connection = JdbcUtil6.getConnection();
//获取预处理sql语句搬运工
PreparedStatement preparedStatement = connection.prepareStatement(sql);
//获取参数元数据
ParameterMetaData parameterMetaData = preparedStatement.getParameterMetaData();
//获取参数个数
int parameterCount = parameterMetaData.getParameterCount();
//占位符具体化
if(parameters!=null && parameterCount==parameters.length){
for (int i = 1; i <= parameterCount; i++) {
preparedStatement.setObject(i,parameters[i-1]);
}
}
//执行sql语句
int i = preparedStatement.executeUpdate();
//关闭流资源
JdbcUtil6.close(connection,preparedStatement);
System.out.println(i);
//返回受影响的行数
return i;
}
//查询
public<T> List<T> query(String sql,Object [] parameters, Class<T> cls) throws SQLException {
//1.获取数据库连接对象
Connection connection = JdbcUtil6.getConnection();
//2.获取预处理sql语句搬运工
PreparedStatement preparedStatement = connection.prepareStatement(sql);
//3.获取参数元数据对象
ParameterMetaData parameterMetaData = preparedStatement.getParameterMetaData();
//4.获取参数个数
int parameterCount = parameterMetaData.getParameterCount();
//5.占位符具体化
if(parameters!=null && parameterCount==parameters.length){
for (int i = 1; i <= parameterCount; i++) {
preparedStatement.setObject(i,parameters[i-1]);
}
}
//6.执行sql语句
ResultSet resultSet = preparedStatement.executeQuery();
//7.获取结果集元数据
ResultSetMetaData metaData = resultSet.getMetaData();
//15.创建集合
ArrayList<T> list = new ArrayList<>();
//8.遍历数据
while (resultSet.next()){
//9.获取列的个数
int columnCount = metaData.getColumnCount();
//13.创建当前类对象
T t =null;
try {
t = cls.getConstructor(null).newInstance(null);
//10.获取列的名字
for (int i = 1; i <= columnCount; i++) {
String columnName = metaData.getColumnName(i);
//11.获取列的值
Object value = resultSet.getObject(columnName);
//12.将值赋值给当前类对象
BeanUtils.setProperty(t,columnName,value);
}
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
//14.将类对象数据存入集合中
list.add(t);
}
//16.关闭流资源
JdbcUtil6.close(connection,preparedStatement,resultSet);
//17.遍历集合
for (T t : list) {
System.out.println(t);
}
//18.返回集合
return list;
}
}
posted @ 2021-09-01 17:13  张三疯321  阅读(313)  评论(0编辑  收藏  举报