Possible Duplicate:
How to get the generated SQL-Statement from a SqlCommand-Object?
I would like to know how to retrieve the SQL query that was executed by a Table Adapter for logging purposes.
For example:
Input:
RandomTableAdapter tableAdapter = new RandomTableAdapter();
tableAdapter.Insert("val","val","val","val");
Output:
What I would like to log is the insert statement, which is generated by the table adapter in order to execute the insert command.
Insert INTO RandomTable VALUES ('val', 'val', 'val', 'val');
How can I do this? Does anyone have any suggestions regarding this?
You can use this workaround with replace ParameterName with its value
but it not good because you need to manage value formatting by your own, and it can be slow
and you will need to get parameters after Insert is executed
code:
var usersTableAdapter = new testDataSetTableAdapters.usersTableAdapter();
usersTableAdapter.Insert(4, "home", "origin", "email@host.com", "realname", "spec", 1, "username", "usernick", "whereform");
var cmd = usersTableAdapter.Adapter.InsertCommand;
var text = cmd.CommandText;
var sb = new StringBuilder(text);
foreach (SqlParameter cmdParam in cmd.Parameters)
{
if (cmdParam.Value is string)
sb.Replace(cmdParam.ParameterName, string.Format("'{0}'", cmdParam.Value));
else
sb.Replace(cmdParam.ParameterName, cmdParam.Value.ToString());
}
Console.WriteLine(sb.ToString());
来源:https://stackoverflow.com/questions/10781801/how-to-get-the-executing-sql-query-from-a-table-adapter