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 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置