简体   繁体   English

如何在ASP.NET/C#的SQL查询中使用“&” VB运算符?

[英]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)

BUT DON'T DO THAT! 但是不要这样做!

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.

相关问题 如何在asp.net C#中创建从URL获取参数的SQL查询# - How can I create SQL Query which Takes Parameters from URL in asp.net C# asp.net C#中的SQL IN运算符 - SQL IN operator in asp.net C# 我可以合并ASP.Net VB和ASP.Net C# - Can I merge ASP.Net VB and ASP.Net C# 如何在C#asp.net中使用SqlDataReader对SQL Server查询使用参数,该参数是查询本身的一部分 - How to use a parameter for a SQL Server query that is part of the query itself using SqlDataReader in C# asp.net 如何在ASP.NET C#Web应用程序中使用ASP.NET VB页面 - How to use asp.net vb pages in asp.net c# web application 如何使用 ASP.NET C# 将 SQL 查询的结果存储在会话变量中以便以后使用 - How to store the result of SQL query in Session Variable using ASP.NET C# to use it later 如何在同一个ASP.NET Web窗体应用程序中使用c#和vb.net代码? - How can I have c# and vb.net code behinds in the same ASP.NET Web Forms application? 如何在不使用ASPNETDB.MDF的情况下使用角色管理 - asp.net/c# - how can i use rolemanagement without the use of ASPNETDB.MDF - asp.net/c# 我应该如何在ASP.net中使用SQL查询的结果? - How should I use result of SQL query in ASP.net? C#EF ASP.NET Web API超时 - 如何调用长时间运行的查询? - C# EF ASP.NET Web API timeout - how can I call a long running query?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM