How to get the executing SQL query from a table adapter? [duplicate]

馋奶兔 提交于 2019-12-07 14:37:45

问题


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?


回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!