简体   繁体   中英

How can I use '&' VB operator in a SQL query in ASP.NET / C#?

How can I use '&' VB operator in C# Asp.net SQL query from the following code. The below code is of VB.

query = "select top 1 * from Name Where ID=" & Order(0)

My code:

SqlCommand cmd = new SqlCommand("select top(1) * from Name where ID=", & order[0], con)

Which throws me a syntax error. I tried using '+' in between where ID=", + order[0], con) but it wasn't able to get the value stored in order[0]. Please help. Thank you.

That C# equivalent to VB's & string concatenation operator will look like this:

SqlCommand cmd = new SqlCommand("select top 1 * from Name where ID=" + order[0].ToString(), con)

BUT DON'T DO THAT!

That technique is crazy-vulnerable to sql injection attacks. For this and other reasons you should build the query like this instead:

SqlCommand cmd = new SqlCommand("select top 1 * from Name where ID= @ID", con)
cmd.Parameters.Add("@ID", SqlDbType.Int).Value = order[0];

string interpolation is a much more readable way to go here. While I wouldn't necessarily build a dynamic SQL string at all out of concern for exposing to SQL injection attacks, the way to build a string like what you're looking for in a more readable manner would be to do something like:

var statement = $"select top(1) * from Name where Id={orders[0]}";

您只需要@开始查询:

SqlCommand cmd = new SqlCommand(@"select top(1) * from Name where ID='"+ order[0] +"'", con);

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