要打印完整的 SQL 语句,你可以使用 Java 查询包装器(如 JDBC)中的 PreparedStatement 对象的 toString() 方法。下面是一个示例代码:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Main {
    public static void main(String[] args) {
        try {
            // 连接数据库
            Connection connection = DriverManager.getConnection('jdbc:mysql://localhost:3306/mydatabase', 'username', 'password');

            // 创建 SQL 查询语句
            String sql = 'SELECT * FROM mytable WHERE id = ?';

            // 创建 PreparedStatement 对象
            PreparedStatement preparedStatement = connection.prepareStatement(sql);

            // 设置参数
            preparedStatement.setInt(1, 1);

            // 打印完整的 SQL 语句
            System.out.println(preparedStatement.toString());

            // 执行查询
            ResultSet resultSet = preparedStatement.executeQuery();

            // 处理查询结果
            while (resultSet.next()) {
                // 处理每一行数据
                // ...
            }

            // 关闭连接
            resultSet.close();
            preparedStatement.close();
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

在上述示例中,我们使用 preparedStatement.toString() 方法打印了完整的 SQL 语句。注意,这个方法是非标准的,它的输出格式可能会因数据库驱动程序的不同而有所不同。


原文地址: https://www.cveoy.top/t/topic/pmoj 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录