本帖最后由 Aiming 于 2023-7-23 23:24 编辑
- package testMysql;
- import com.alibaba.druid.pool.DruidDataSourceFactory;
- import org.apache.logging.log4j.LogManager;
- import org.apache.logging.log4j.Logger;
- import org.springframework.jdbc.core.JdbcTemplate;
- import javax.sql.DataSource;
- import java.io.InputStream;
- import java.sql.Connection;
- import java.sql.SQLException;
- import java.util.List;
- import java.util.Map;
- import java.util.Properties;
- /**
- * JDBC工具类 使用Druid连接池
- */
- public class JDBCUtils {
- private static DataSource connection;
- public static Logger log= LogManager.getLogger(JDBCUtils.class);
- static {
- try {
- //1.加载配置文件
- Properties pro = new Properties();
- //使用ClassLoader加载配置文件,获取字节输入流
- InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid224.properties");
- pro.load(is);
- //2.初始化连接池对象
- connection = DruidDataSourceFactory.createDataSource(pro);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- /**
- * 获取连接池对象
- */
- public static DataSource getDataSource(){
- return connection;
- }
- /**
- * 获取连接Connection对象
- */
- public static Connection getConnection() throws SQLException {
- return connection.getConnection();
- }
- public static void main(String[] args) throws SQLException {
- String sql="select a.task_role,a.task_name,a.actual_status,task_id,a.* from abs_task.abs_task a where a.poord_package_num ='000A181130000020' ORDER BY create_Time desc;";
- List<Map<String, Object>> sqlList;
- //声明JDBCTemplate对象共用
- JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
- sqlList=template.queryForList(sql);
- log.info(sqlList);
- for (int i=0;i<sqlList.size();i++){
- Map<String, Object> sqlMap=sqlList.get(i);
- //log.info("结果:"+sqlMap.getClass());
- for (String key:sqlMap.keySet()) {
- if (key.contains("task_id")) {
- System.out.println(key + ":" + sqlMap.get(key));
- }
- }
- }
- getConnection();
- }
- }
复制代码
|