gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 15:13:05 24 4
gpt4 key购买 nike

我在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com