cyoeki 2016-03-20 03:07 采纳率: 100%
浏览 1986
已采纳

空指针异常,初始化异常!求助!

 public class JdbcUtils {
    private static Properties properties = null;
    static{
        try {
            InputStream inp = JdbcUtils.class.getClassLoader().getResourceAsStream("dbconfig.properties");
            properties = new Properties();
            properties.load(inp);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        try {
            Class.forName(properties.getProperty("driverClassName"));
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
    public static Connection getConnection() throws IOException, ClassNotFoundException, SQLException{
        return DriverManager.getConnection(properties.getProperty("url"), properties.getProperty("username"), properties.getProperty("password"));
    }   
}



public class AccountDao {
    public void updateBalance(Connection con,String name,double balance){
        try {
            String sql = "update account set balance=balance+? where name=?";
            PreparedStatement pstmt = con.prepareStatement(sql);
            pstmt.setString(2, name);
            pstmt.setDouble(3, balance);
            pstmt.executeUpdate();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}




public class Demo1 {
    public void transfer_account(String from,String to,double money) {
        Connection con =null;

        try {
            con=JdbcUtils.getConnection();
            System.out.println("falt");
            con.setAutoCommit(false);
            AccountDao dao = new AccountDao();
            dao.updateBalance(con,from, -money);
            dao.updateBalance(con,to, money);
            con.commit();
            con.close();
        } catch (Exception e) {
            try {
                con.rollback();
                con.close();
            } catch (SQLException e1) {
                throw new RuntimeException(e);
            }
        }finally{
            if(con!=null)
                try {
                    con.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
        }
    }
    @Test
    public void fun2() {
        transfer_account("zs", "ls", 100);  
    }
}

测试时出现初始化异常和空指针异常,实在找不到问题在哪……

  • 写回答

3条回答

  • 毕小宝 博客专家认证 2016-03-20 03:11
    关注
      看异常信息,定位异常语句,然后把可能是空的对象进行判空操作。其实空指针异常是很好解决的,调用对象的.操作却没有new操作的对象。耐心的再找找呗。
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀