如何在绑定参数后打印在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
答案 0 :(得分:4)
默认情况下这是不可能的,因此您可以编写一个扩展名,用参数值替换参数名称。
例如:
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();
}
}