weixin_43306301 2019-05-06 22:33 采纳率: 50%
浏览 509
已采纳

dbcp中报空指针异常如何解决?

package com.dtz.dbcp;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.commons.dbcp2.BasicDataSource;
import org.junit.Test;

public class DBCPDemo1 {
    @Test
    public void testDBCPDemo1() {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        try {
            @SuppressWarnings("resource")
            BasicDataSource dataSource = new BasicDataSource();
            dataSource.setDriverClassName("com.mysql.jdbc.Driver");
            dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/stu");
            dataSource.setUsername("root");
            dataSource.setPassword("033516");

            conn = dataSource.getConnection();
            String sql = "select * from stu";
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            while (rs.next()) {
                System.out.println(rs.getString("sname"));
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                rs.close();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                ps.close();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                conn.close();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }


}

图片说明

  • 写回答

2条回答 默认 最新

  • weixin_43306301 2019-07-31 16:45
    关注

    这里主要是mysql的驱动包版本过低(5.0)或dbcp的版本过高(2.7),dbcp2.0以上需要mysql的驱动包为5.1.3以上

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 k8s集群重启后,kubelet一直报systemctl restart kubelet.service "Failed to delete cgroup paths"
  • ¥15 微信小程序构建工具类发布到npm,install后报错
  • ¥15 amesim液压仿真问题
  • ¥15 python解析json文件时报错
  • ¥15 MATLAB优化设计
  • ¥15 ANN预测模型 200大米
  • ¥20 优秀学生的问题 oj java
  • ¥15 scratch-gui 如何集成进 react native
  • ¥15 把全局悬浮窗改为局内悬浮窗
  • ¥15 Excel vba编程调用word如何读取换行符