如何在C#上从ODBC获取带参数的查询

本文关键字:参数 查询 获取 ODBC 上从 | 更新日期: 2023-09-27 18:26:34

绑定参数后,如何在C#上打印从ODBC解析的查询?这是示例代码:

cmd.CommandText = "SELECT * from user WHERE id = ?";
cmd.Prepare();
cmd.Parameters.Add("@id", OdbcType.Int).Value = 2;
OdbcDataReader reader = cmd.ExecuteReader();
string query = cmd.????; // Here i need a method for get a full query

如何在C#上从ODBC获取带参数的查询

默认情况下这是不可能的,因此您可以编写一个扩展,用参数值替换参数名称。

例如:

internal class Program
{
    private static void Main(string[] args)
    {
        OdbcConnection connection = new OdbcConnection("");
        OdbcCommand command = new OdbcCommand("SELECT * FROM Table WHERE Id = ? AND Column = ?", connection);
        command.Parameters.Add("@id", OdbcType.Int).Value = 2;
        command.Parameters.Add("@text", OdbcType.VarChar).Value = "test";
        string preparedSql = command.GetPreparedSql();
        // preparedSql = 
        Console.ReadLine();
    }
}
public static class OdbcExtensions
{
    public static string GetPreparedSql(this OdbcCommand command)
    {
        string[] splitted = command.CommandText.Split(new[] {'?'}, StringSplitOptions.RemoveEmptyEntries);
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < splitted.Length; i++)
        {
            builder.Append(splitted[i]);
            OdbcParameter param = command.Parameters[i];
            switch (param.DbType)
            {
                case DbType.Boolean:
                    builder.Append(Convert.ToBoolean(param.Value) ? "1" : "0");
                    break;
                case DbType.AnsiString:
                    builder.AppendFormat("'{0}'", param.Value);
                    break;
                default:
                    builder.Append(param.Value);
                    break;
            }
            builder.Append(" ");
        }
        return builder.ToString();
    }
}