[英]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. 如何从以下代码在C#Asp.net SQL查询中使用'&'VB运算符。 The below code is of VB.
下面的代码是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. 我尝试
where ID=", + order[0], con)
之间使用'+',但是它无法获取存储在order [0]中的值。请帮助。谢谢。
That C# equivalent to VB's &
string concatenation operator will look like this: 与VB的
&
字符串连接运算符等效的C#看起来像这样:
SqlCommand cmd = new SqlCommand("select top 1 * from Name where ID=" + order[0].ToString(), con)
That technique is crazy-vulnerable to sql injection attacks. 这项技术很容易受到sql注入攻击的攻击。 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:
尽管不必出于暴露于SQL注入攻击的考虑而完全构建动态SQL字符串,但是以更易读的方式构建类似于您正在寻找的字符串的方法将是执行以下操作:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.