Druid数据源获取Connection报空指针

本文讲述了作者在使用DruidDataSource时遇到空指针异常,通过打印数据源确认非空,随后升级MySQL、Druid及JDBC驱动版本至最新(8.0.25等),最终解决了问题的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、问题描述

数据源:DruidDataSource  druidDataSource 

操作:druidDataSource.getConnection()

结果:空指针

二、解决过程

1.打印druidDataSource,发现非null;

2.更新mysql、druid、mysql-connector-java版本,旧版本分别为5.5.28、1.0.26、5.1.28,新版本:8.0.25、1.2.6、8.0.21;

3.更新版本后问题解决。

public class JdbcMytest { static DataSource dataSource; public static void main(String[] args) throws Exception { //DataSource dataSource = new DruidDataSource(); JdbcMytest demo = new JdbcMytest(); demo.test(); //Class.forName("com.mysql.cj.jdbc.Driver"); //Connection connection = DriverManager.getConnection("jdbc:mysql:///atguigu", "root", "123456"); Connection connection = JdbcMytest.getConnection(); String sql = "select e.did,e.ename,e.gender,e.salary from t_employee e join t_department d on e.did = d.did where salary >8000 group by e.gender "; PreparedStatement preparedStatement = connection.prepareStatement(sql); ResultSet resultSet = preparedStatement.executeQuery(); while (resultSet.next()){ int anInt = resultSet.getInt(1); Object ename = resultSet.getObject("ename"); String gender = resultSet.getString("gender"); int anInt1 = resultSet.getInt(4); System.out.println(anInt+"\t"+ename+"\t"+gender+"\t"+anInt1); } resultSet.close(); preparedStatement.close(); connection.close(); } /*创建连接池,使用连接池去拿连接对象连接数据库,就不用每次创建连接对象避免内存开销*/ public void test(){ InputStream resourceAsStream = JdbcUtils.class.getClassLoader().getResourceAsStream("properties"); Properties properties = new Properties(); try { properties.load(resourceAsStream); } catch (IOException e) { throw new RuntimeException(e); } try { dataSource = DruidDataSourceFactory.createDataSource(properties); } catch (Exception e) { throw new RuntimeException(e); } } public static Connection getConnection() { try { return dataSource.getConnection(); } catch (SQLException e) { throw new RuntimeException(e); } } }
最新发布
07-04
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值