本人小白一枚,欢迎大家一起讨论学习,如有错误,还望大家指教。
通过上一篇的学习,我们发现在操作数据库时会有很多重复的代码,为了解决这个问题,我们将要写一个工具类来简化代码。
public class JDBCUtils {
private static String url;
private static String username;
private static String password;
static {
try {
// 用Properties来配置数据库的用户名和密码
Properties properties = new Properties();
// 可以使用类加载器ClassLoader来获取src路径下的jdbc.properties文件
ClassLoader loader = JDBCUtils.class.getClassLoader();
URL resource = loader.getResource("jdbc.properties");
properties.load(new FileReader(resource.getPath()));
// 获取配置文件中的值
url = properties.getProperty("url");
username = properties.getProperty("username");
password = properties.getProperty("password");
// 注册驱动
Class.forName(properties.getProperty("driver"));
} catch (Exception e) {
e.getStackTrace();
}
}
/**
* 获取数据库连接对象
* @return
*/
public static Connection getConnection() {
try {
return DriverManager.getConnection(url, username, password);
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
/**
* 释放资源
* @param statement 执行sql对象
* @param connection 数据库连接对象
*/
public static void closeResources(Statement statement, Connection connection) {
if (statement != null) {
try {
statement.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 释放资源
* @param resultSet 结果集对象
* @param statement 执行sql对象
* @param connection 数据库连接对象
*/
public static void closeResources(ResultSet resultSet, Statement statement, Connection connection) {
if(resultSet != null) {
try {
resultSet.close();
} catch (Exception e) {
e.printStackTrace();
}
}
closeResources(statement, connection);
}
}
练习
例子:登录案例,用户通过键盘录入用户名和密码来进行登录操作,我们会使用上面的工具类。
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入用户名:");
String username = scanner.nextLine();
System.out.println("请输入密码:");
String password = scanner.nextLine();
if (login(username, password)) {
System.out.println("登录成功!");
} else {
System.out.println("用户名或密码失败!");
}
}
public static boolean login(String username, String password) {
if (username == null || password == null) {
return false;
}
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
try {
connection = JDBCUtils.getConnection();
String sql = "SELECT * FROM user model WHERE model.username = ? AND model.password = ?";
statement = connection.prepareStatement(sql);
statement.setString(1, username);
statement.setString(2, password);
resultSet = statement.executeQuery();
return resultSet.next();
} catch (Exception e) {
e.printStackTrace();
} finally {
// 释放资源
JDBCUtils.closeResources(resultSet, statement, connection);
}
return false;
}
成功
请输入用户名:
admin
请输入密码:
123456
登录成功!
失败
请输入用户名:
123
请输入密码:
123
用户名或密码失败!
简述:一个包含多个步骤的业务操作。如果这个业务操作被事务管理,则这多个步骤要么同时成功,要么同时失败。
事务四个特性 ACID:原子性、一致性、隔离性、持久性
操作:
- 开启事务
- 提交事务
- 回滚事务
使用Connection对象来管理事务
- 开启事务:setAutoCommit(boolean autoCommit) :调用该方法设置参数为false,即开启事务
- 在执行sql之前开启事务
- 提交事务:commit()
- 当所有sql都执行完提交事务
- 回滚事务:rollback()
- 在catch中回滚事务
在上面的user表中增加一个工资(salary字段),类型为int,并且添加数据
我们模拟张三为李四进行转账500业务,即张三工资变为500,李四变为1500。
public static void main(String[] args) {
Connection connection = null;
PreparedStatement statement = null;
try {
connection = JDBCUtils.getConnection();
// 开启事务
connection.setAutoCommit(false);
String sql = "UPDATE user set salary = ? WHERE username = ?";
statement = connection.prepareStatement(sql);
statement.setInt(1, 500);
statement.setString(2, "张三");
statement.executeUpdate();
// 手动抛出异常
int i = 1 / 0;
statement.setInt(1, 1500);
statement.setString(2, "李四");
statement.executeUpdate();
System.out.println("转账成功");
// 提交事务
connection.commit();
} catch (Exception e) {
e.printStackTrace();
System.out.println("转账失败");
// 回滚事务
try {
if (connection != null) {
connection.rollback();
}
} catch (SQLException e1) {
e1.printStackTrace();
}
} finally {
// 关闭资源
JDBCUtils.closeResources(statement, connection);
}
}
打印结果
转账失败
java.lang.ArithmeticException: / by zero
at affair.Demo.main(Demo.java:23)
我们手动抛出异常之后,再次查询,发现张三与李四的工资都没有发生改变,如果我们不使用事务,如果在转账期间发生异常,会发生张三转账钱被扣除,而李四的账户却没有增加,由此而知,事务的存在时多么的重要!