简体   繁体   English

使用string.format动态创建SQL查询

[英]SQL query formation dynamically, using string.format

I have a serious problem of formatting queries, it may result in SQL injection too, I saw some similar qstns, but not sure how could i use it in C# as I am new to it. 我在格式化查询时遇到了一个严重的问题,它也可能导致SQL注入,我看到了一些类似的qstns,但是由于我是新手,所以不确定如何在C#中使用它。 I use c#,Odbc command 我使用c#,Odbc命令

I have 3 strings like qry ="select description from TableA" , qryOrder = " order by description" , qryAppend = " where ID = '{0}' order by description\\", _selectedPlantID" provided _selectedId is another variable, Now I want to use these variables to form diff queries at different scenarios, for eg, qry + qry order , or qry + qryAppend . 我有3个字符串,例如qry ="select description from TableA" , qryOrder = " order by description" , qryAppend = " where ID = '{0}' order by description\\", _selectedPlantID"前提是_selectedId是另一个变量,现在我想要在不同情况下使用这些变量来形成差异查询,例如qry + qry orderqry + qryAppend

Since _selectedPlantId is also needed, I use string.Format as : 由于还需要_selectedPlantId ,因此我将string.Format用作:

_cmd.CommandText = "string.Format(\"" + qry + qryAppend + ")";

But its not working. 但是它不起作用。 any solution ? 有什么办法吗? Error is SQL syntax error with quotes 错误是带引号的SQL语法错误

thanks in advance !! 提前致谢 !!

Simply put, this should make it work. 简而言之,这应该使其工作。 You'll need two variables (bool), I'll explain later why: 您将需要两个变量(布尔),稍后我将解释原因:

var shouldOrder = true;
var shouldAppend = true;

_cmd.CommandText = String.Format(
    "{0} {1} {2}",
    qry,
    shouldOrder ? qryOrder : String.Empty,
    shouldAppend ? qryAppend : String.Empty
);

These two variables ( shouldOrder and shouldAppend ) will help you with the "diff queries at different scenarios" as you've said. 正如您所说,这两个变量( shouldOrdershouldAppend )将帮助您解决“在不同情况下的差异查询”。

Providing these variables with true or false will change what text goes into the String.Format and will change query accordingly. 为这些变量提供true或false将会更改将哪些文本输入到String.Format中,并相应地更改查询。

So, if you use shouldOrder = false; 因此,如果使用shouldOrder = false; the query command won't get the order part. 查询命令将不会获得订单部分。 Setting shouldAppend = false; 设置shouldAppend = false; will avoid including the extra part (append) into the SQL command. 将避免将多余的部分(附加)添加到SQL命令中。

Now, be careful! 现在,要小心!

This won't solve your SQL injection problem. 这不会解决您的SQL注入问题。 I've just shown a quick fix. 我刚刚显示了一个快速修复。

To avoid SQL injections, you'll have to change your SQL command and you cannot use String.Format anymore. 为了避免SQL注入,您必须更改SQL命令,并且不能再使用String.Format。

To understand how to do that, take a look into DGibbs comment. 要了解如何执行此操作,请查看DGibbs注释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM