作者:ErnastoChen | 来源:互联网 | 2023-10-13 05:37
importcom.alibaba.druid.pool.DruidDataSource;importcom.alibaba.druid.pool.DruidPooled
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.CaseFormat;
import org.apache.commons.beanutils.BeanUtils;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
/**
* 封装为任何JDBC数据库的任何查询都可以使用该工具类的方法
* id为主键
* select count(*) from t; 单行单列
* select * from t where id = '1001'; 单行多列
* select count(*) from t group by tm_id; 多行单列
* select * from t; 多行多列(实现它即可实现上面的)
*多行多列:使用list集合存储,因为每行数据都是相同格式,对于列(不确定),所以使用泛型
*/
public class JdbcUtil {
//Class clz:用于给泛型构建对象. boolean underScoreToCamel:用于判断是否进行格式转换
public static List queryList(Connection connection,String sql,Class clz, boolean underScoreToCamel) throws Exception {
//1.创建集合用于存放结果数据
ArrayList list = new ArrayList<>();
PreparedStatement preparedStatement =null;
ResultSet resultSet =null;
try {
//2.预编译SQL
preparedStatement = connection.prepareStatement(sql);
//3.执行SQL查询
resultSet = preparedStatement.executeQuery();
//4.遍历查询结果集,将每行数据封装为T对象并放入集合
//通过元数据拿到列信息
ResultSetMetaData metaData = resultSet.getMetaData();
int columnCount = metaData.getColumnCount();
//4.1 行遍历
while (resultSet.next()){
//构建T对象(每一行是一个T,所以在行遍历下构建)
T t = clz.newInstance();
//4.2列遍历
for (int i = 0; i //获取列名,jdbc中下标以1开始
String columnName = metaData.getColumnName(i + 1);
//通过列名拿到值
Object value = resultSet.getObject(columnName);
//给T对象赋值(把每一列加进去,所以在列遍历下赋值)
//如果需要转化列名格式
if (underScoreToCamel){
//Google下的转换包 将下划线转为小驼峰
columnName = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, columnName.toLowerCase());
}
//给泛型对象赋值,使用BeanUtils工具类
BeanUtils.setProperty(t,columnName,value);
}
//将T对象加入集合
list.add(t);
}
} finally {
if (resultSet !=null){
resultSet.close();
}
if (preparedStatement!=null){
preparedStatement.close();
}
}
//5.返回集合
return list;
}
public static void main(String[] args) throws Exception {
//获取连接
DruidDataSource dataSource = DruidDSUtil.createDataSource();
DruidPooledConnection cOnnection= dataSource.getConnection();
List queryList = queryList(connection,
"select * from GMALL220212_REALTIME.DIM_BASE_TRADEMARK where id='15'",
JSONObject.class,
true);
for (JSONObject jsonObject : queryList) {
System.out.println(jsonObject);
}
connection.close();
}
}