简体   繁体   中英

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. I use c#,Odbc command

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 .

Since _selectedPlantId is also needed, I use string.Format as :

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

But its not working. any solution ? Error is SQL syntax error with quotes

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.

Providing these variables with true or false will change what text goes into the String.Format and will change query accordingly.

So, if you use shouldOrder = false; the query command won't get the order part. Setting shouldAppend = false; will avoid including the extra part (append) into the SQL command.

Now, be careful!

This won't solve your SQL injection problem. 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.

To understand how to do that, take a look into DGibbs comment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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