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

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条回答 默认 最新

相关推荐 更多相似问题