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);
}
}
测试时出现初始化异常和空指针异常,实在找不到问题在哪……