问题描述
- 使用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; } }
解决方案
没有连接,是不是你的连接池配置不对
时间: 2024-09-19 09:23:41