cyoeki
2016-03-20 03:07
采纳率: 50%
浏览 2.0k
已采纳

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

 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条)

相关推荐 更多相似问题