Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
230 views
in Technique[技术] by (71.8m points)

c# - How to pass a custom subquery to SQL command in ADO.NET?

I often have to construct long and difficult queries "in code". I know, that I can pass any parameters using SqlDataAdapter.SelectCommand.Parameters.Add() method. But what should I do if i need in some cases make multiple concatenations like this:

var subquery = ConstructSubquery(param1, paramN);
query += subquery;

And so on. Code analyzer in VS offers me to use parameters instead of simple string concatenation, but something like

dataBaseSQL.SqlDataAdapter.SelectCommand.Parameters.Add("@subquery", SqlDbType.VarChar).Value = subquery;
//subquery = "WHERE param1 IN ('A', 'Z') AND param2 <> param3" (for example...)

does not work, of course! Queries are dynamic, subqueries are generated by special functions. What is the best decision?

question from:https://stackoverflow.com/questions/65849478/how-to-pass-a-custom-subquery-to-sql-command-in-ado-net

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Parameters are for values, not for statements (or pieces of statements).

A and Z are values that can be put in a parameter (let's say @value1 and @value2) (and we will ignore the complexity of doing the IN operator using a variable number of parameters... there is an hard limit on the number of parameters in SQL Server, 2100). So for example WHERE param1 IN (@value1, @value2) is perfectly ok...

You can't put the whole WHERE param1 IN (@value1, @value2) in a parameter.

You shouldn't/mustn't let the user write SQL statements or piece of SQL statements (so no SELECT or WHERE written by the user), it is very highly insecure, and I don't think it can really be secured.

Even letting the user fill the name of columns to be selected can be insecure. Always ask yourself: what happens if the user writes, as the column name, for example?

-- DROP TABLE SomeTable --

And even letting the user select the column names from a "closed list" could be insecure, because 9 times out of 10 you won't check if the user manipulated the javascript of the page to write whatever he wants in the combobox/listbox (it is quite easy... press F12 on Chrome and the whole javascript of the page is in your hands).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...