cyoeki
cyoeki
采纳率50%
2016-05-03 11:00 阅读 1.5k
已采纳

使用C3P0出现错误…NullPointerException…

图片说明

测试的是fun1()方法

public void fun1(){
        User user = new User(4, "cyoeki2", "123", "xzs");
        addUser(user);
    }
    public void addUser(User user){
        QR qr = new QR(JdbcUtils.getDataSource());
        String sql = "insert into users values(?,?,?,?)";
        Object[] params ={user.getId(),user.getUsername(),user.getPassword(),user.getNickname()};
        qr.update(sql, params);
    }


    public class QR<T> {
    private DataSource dataSource;
    public QR() {
        super();
    }
    public QR(DataSource dataSource) {
        super();
        this.dataSource = dataSource;
    }
    public int update(String sql, Object...params){
        Connection con = null;
        PreparedStatement pstmt = null;
        try {
            con=dataSource.getConnection();
            pstmt = con.prepareStatement(sql);
            initParams(pstmt,params);
            return pstmt.executeUpdate();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally{
            try{
            if(pstmt!=null)pstmt.close();
            if(con!=null)con.close();;
            }catch(SQLException e){
                throw new RuntimeException(e);
            }
        }
    }
    private void initParams(PreparedStatement pstmt,Object...params) throws SQLException{
        for(int i=0;i<params.length;i++){
            pstmt.setObject(i+1, params[i]);
        }
    }
    public T query(String sql,RsHandler rs,Object...params){
        return null;
    }
}

interface RsHandler<T>{
    public T handle(ResultSet rs);
} 


 public class JdbcUtils {
    private static ComboPooledDataSource dataSorce = new ComboPooledDataSource();
    public static Connection getConnection() throws SQLException{
        return dataSorce.getConnection();
    }
    public static DataSource getDataSource(){
        return dataSorce;
    }
}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    jhfsdfs machineShunMing 2016-05-03 11:33

    没有连接,是不是你的连接池配置不对

    点赞 评论 复制链接分享

相关推荐