Get raw sql statement with DbExtensions SqlBuilder

别等时光非礼了梦想. 提交于 2020-01-17 07:52:27

问题


I'm using the SqlBuilder to build a dynamic sql statement where the SELECT and WHERE clauses vary. The query is built like this:

 SqlBuilder sb = new SqlBuilder();

 sb.SELECT("id, name");
 sb.FROM("products");
 sb.WHERE("name LIKE {0}", new object[] { "a%" });

Once I've got the SqlBuilder ready, I would like to get the raw sql statement. However, the ToString() method returns a string which might look like this:

SELECT id, name FROM products WHERE name LIKE {0}

I need the raw sql with the parameters set, ie:

SELECT id, name FROM products WHERE name LIKE 'a%'

Is it possible using DbExtensions SqlBuilder?


回答1:


You need to call ToCommand passing a provider factory or a connection instance, e.g:

DbCommand command = query.ToCommand(SqlClientFactory.Instance);

In v6, you have to use Database:

var db = new Database();
IDbCommand command = db.CreateCommand(query);



回答2:


The DbExtensions help page has this code:

var query = new SqlBuilder()
   .SELECT("*")
   .FROM("Products")
   .WHERE("Name LIKE {0}", "A%")

This is different to yours. (I know the method has params object[] as the signature, but params don't necessarily work as you think.) Change your WHERE to match theirs.



来源:https://stackoverflow.com/questions/27187755/get-raw-sql-statement-with-dbextensions-sqlbuilder

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