oledb/ado.net: Get the command's text, with all parameters replaced

和自甴很熟 提交于 2019-12-23 14:22:22

问题


Is it possible to get the text of an OleDbCommand with all parameters replaced with their values? E.g. in the code below I'm looking for a way to get the query text

SELECT * FROM my_table WHERE c1 = 'hello' and c2 = 'world'

after I finished assigning the parameters.

var query = "SELECT * FROM my_table WHERE c1 = ? and c2 = ?";
var cmd = new OleDbCommand(query, connection);
cmd.Parameters.Add("@p1", OleDbType.WChar).Value = "hello";
cmd.Parameters.Add("@p2", OleDbType.WChar).Value = "world";

回答1:


No: you have to iterate through the parameters collection yourself, doing a string.Replace() to get the equivalent. It's particularly painful when you have to use the ? syntax rather than the @parametername syntax.

The reason for this is that the full string is never assembled. The parameters and sent to the server and treated as data, and are never included in the string.

All the same, I for one understand your pain. It would have been nice if they included some kind of .ComposeSQL() method you could call for debugging purposes, that perhaps also produces a compiler warning to help avoid use in production.




回答2:


If you just need to see what query was executed and dont need to work with it programmatically, you can use SQL Profiler.



来源:https://stackoverflow.com/questions/178857/oledb-ado-net-get-the-commands-text-with-all-parameters-replaced

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