c# - 参数化查询(C#、Oracle): How to produce a more readable representation?

标签 c# sql oracle parameterized

我在 C# 代码中使用参数化查询与 Oracle 数据库交互。我该怎么做才能以更具可读性的方式记录语句?

假设我有一个参数化查询,例如:

INSERT INTO PERSON (ID, NAME, BIRTHDATE) VALUES (:id, :name, :birthdate)

理想情况下,我希望看到所有参数都被替换的日志条目,这样我就可以复制并粘贴该语句供以后使用:

INSERT INTO PERSON (ID, NAME, BIRTHDATE) VALUES (23, ‘Mike’, TO_DATE('2003/07/09', 'yyyy/mm/dd')

我目前的做法是打印出参数化查询的字符串,然后遍历所有参数并使用 ToString()。如果有很多参数,这有点难以阅读。它会产生类似的东西:

INSERT INTO PERSON (ID, NAME, BIRTHDATE) VALUES (:id, :name, :birthdate) [:id=23, :name=Mike, birthdate=2004/07/09 00:00:00]

我计划的另一种方法是使用 string.Replace() 函数来替换参数占位符。但也许有更好的方法来做到这一点?

提前致谢。

编辑 1:

我觉得最好提供一些代码示例。

我正在使用这种形式的参数化查询(注意:我正在使用 log4net):

        using (OracleConnection connection = new OracleConnection(connectionString))
        using (OracleCommand command = new OracleCommand(statement, connection))
        {
            command.Parameters.AddWithValue(":id", id);
            command.Parameters.AddWithValue(":name", name);
            command.Parameters.AddWithValue(":birthdate", birthdate);
            command.Connection.Open();
            log.DebugFormat("Executing statement: {0}.", command.CommandText);
            // there I would add some more code to iterate over
            // the parameters and print them out
            command.ExecuteNonQuery();
            command.Connection.Close();
        }

我正在寻找一种方法来注销 oracle 命令对象正在使用的语句。我目前的方法(参见问题)还不是很令人满意,因为可读性不强。

我希望有一些 API(甚至可能在 OracleClient 命名空间中)可以帮助我解析参数化查询。我可以做一些更复杂的字符串替换或正则表达式,但我想收集一些知识。我已经对此进行了一些研究,但没有找到任何东西。

最佳答案

也许值得看看它在 NHibernate 中的完成方式 source .

找到名为“GetCommandLogString(IDbCommand command)”的函数,您几乎可以复制/粘贴它:p

protected string GetCommandLogString(IDbCommand command)
{
    string outputText;

    if (command.Parameters.Count == 0)
    {
        outputText = command.CommandText;
    }
    else
    {
        StringBuilder output = new StringBuilder();
        output.Append(command.CommandText);
        output.Append("; ");

        IDataParameter p;
        int count = command.Parameters.Count;
        for (int i = 0; i < count; i++)
        {
            p = (IDataParameter) command.Parameters[i];
            output.Append(string.Format("{0} = '{1}'", p.ParameterName, p.Value));

            if (i + 1 < count)
            {
                output.Append(", ");
            }
        }
        outputText = output.ToString();
    }
    return outputText;
}

关于c# - 参数化查询(C#、Oracle): How to produce a more readable representation?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/453849/

相关文章:

c# - EF代码优先。相关实体未加载

c# - asp.net web 项目中的 Razor View

database - 通过 Excel 连接到 Oracle 数据库

c# - 使用 C# 枚举标志根据按位或运算的值返回一组值

c# - 结构图配置

Mysql 查询不适用于空列

php - 错误是查询连接和日期/时间间隔

c# - Linq To SQL - 具有和分组依据

sql - ORACLE/SQL - 连接3个并非全部互连的表

java - 从oracle 10g列中获取小写字母