Java与MySQL的绝妙结合:打造高效审批流程
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class ApprovalProcessExample {
private static final String DB_URL = "jdbc:mysql://localhost:3306/your_database";
private static final String USER = "your_username";
private static final String PASS = "your_password";
public static void main(String[] args) {
// 示例:更新审批状态
String taskId = "TASK-001";
String status = "Approved";
String comments = "This task has been approved.";
updateApprovalStatus(taskId, status, comments);
}
private static void updateApprovalStatus(String taskId, String status, String comments) {
Connection conn = null;
PreparedStatement pstmt = null;
try {
// 注册JDBC驱动
Class.forName("com.mysql.cj.jdbc.Driver");
// 打开连接
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// 执行查询
String sql = "UPDATE approval_tasks SET status = ?, comments = ? WHERE task_id = ?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, status);
pstmt.setString(2, comments);
pstmt.setString(3, taskId);
// 执行更新
pstmt.executeUpdate();
System.out.println("Task status updated successfully.");
} catch (ClassNotFoundException | SQLException e) {
System.out.println("Error updating task status: " + e.getMessage());
} finally {
// 关闭资源
try {
if (pstmt != null) pstmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
System.out.println("Error closing resources: " + e.getMessage());
}
}
}
}
这段代码展示了如何使用Java连接MySQL数据库,并执行一个更新操作来改变特定任务的审批状态。代码中包含了异常处理,确保在发生错误时能够给出明确的反馈,同时在操作完成后,关闭数据库连接和语句对象以释放资源。
评论已关闭