java实现数据库操作生成日志
Java可以通过JDBC实现数据库操作,同时可以使用Java日志框架记录日志。
以下是一个简单的Java程序,实现了连接MySQL数据库并查询数据的功能,并使用Java自带的日志框架记录日志。
import java.sql.*;
import java.util.logging.*;
public class DatabaseOperation {
private static final Logger LOGGER = Logger.getLogger(DatabaseOperation.class.getName());
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// 注册JDBC驱动
Class.forName("com.mysql.jdbc.Driver");
// 打开连接
LOGGER.log(Level.INFO, "Connecting to the database...");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "password");
// 执行查询
LOGGER.log(Level.INFO, "Executing query...");
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT * FROM users");
// 处理结果集
LOGGER.log(Level.INFO, "Processing result set...");
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
LOGGER.log(Level.INFO, "id:{0}, name:{1}, age:{2}", new Object[]{id, name, age});
}
} catch (ClassNotFoundException | SQLException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
} finally {
// 关闭资源
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
}
}
}
}
在上面的程序中,使用了Java自带的日志框架,定义了一个名为LOGGER的Logger实例。在程序中,使用LOGGER.log(Level.INFO, message, parameters)方法记录日志,其中Level.INFO表示记录信息级别为信息,message表示日志信息,parameters表示日志信息中的参数。在程序中,使用了三个Level.INFO级别的日志信息,分别表示连接数据库、执行查询和处理结果集。如果程序出现异常,将记录异常信息的日志,级别为Level.SEVERE
原文地址: https://www.cveoy.top/t/topic/eO95 著作权归作者所有。请勿转载和采集!