java登录的sql语句,如何获取执行过的所有sql语句
时间: 2023-06-25 14:04:27 浏览: 246
在Java中,可以使用JDBC API来执行SQL语句并获取执行结果。如果要获取执行过的所有SQL语句,可以在代码中使用日志记录来记录每个SQL语句的执行情况。下面是一个示例代码:
```java
import java.sql.*;
import java.util.logging.*;
public class Login {
private static final Logger LOGGER = Logger.getLogger(Login.class.getName());
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydb";
String username = "root";
String password = "password";
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
conn = DriverManager.getConnection(url, username, password);
stmt = conn.createStatement();
String sql = "SELECT * FROM users WHERE username='john' AND password='password'";
rs = stmt.executeQuery(sql);
while (rs.next()) {
// process result set
}
// log SQL statement
LOGGER.log(Level.INFO, "Executed SQL statement: {0}", sql);
} catch (SQLException ex) {
LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException ex) {
LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException ex) {
LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException ex) {
LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
}
}
}
}
}
```
在上面的代码中,我们使用JDBC API来执行SQL语句,并在日志中记录每个SQL语句的执行情况。您可以使用不同的日志记录器和级别,具体取决于您的需求。
阅读全文