Java与MySQL的精准结合:打造高效审批流程
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class ApprovalProcess {
private Connection connect = null;
private PreparedStatement preparedStatement = null;
// 初始化数据库连接
public void init() {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/数据库名", "用户名", "密码");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
// 更新审批状态
public void updateApprovalStatus(String taskId, String status) {
init();
try {
String query = "UPDATE task_table SET status = ? WHERE task_id = ?";
preparedStatement = connect.prepareStatement(query);
preparedStatement.setString(1, status);
preparedStatement.setString(2, taskId);
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (preparedStatement != null) preparedStatement.close();
if (connect != null) connect.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
ApprovalProcess approvalProcess = new ApprovalProcess();
approvalProcess.updateApprovalStatus("TASK-001", "Approved");
}
}
这段代码展示了如何在Java中连接MySQL数据库,并执行一个更新操作来改变特定任务的审批状态。代码中包含了异常处理,以确保即使在遇到错误的情况下,数据库资源也能被正确关闭,防止资源泄露。
评论已关闭