[英]How to insert variable inside a Select statement
string table = "City";
string query = "Select * from '"+table+"'";
This gives me error stating incorrect symbol near ". 这给了我错误说明“。”附近的错误符号。
However, 然而,
string query = "Select * from City";
Gives the proper output. 给出正确的输出。
You just this 你就是这样
string query = "Select * from '"+table+"'";
to be replaced by 被...取代
string query = "Select * from " + table;
Because you Query string is not "Select * from City";
因为查询字符串不是"Select * from City";
While it is forming "Select * from 'City'";
正在形成"Select * from 'City'";
and thus you getting error 因此你得到错误
Best practice would be to use string.format 最佳做法是使用string.format
string table = "City";
string query = string.format("Select * from {0}", table);
You need to form your query like below., 您需要像下面一样形成您的查询。,
string table = "City";
//You don't need to have single quote...
string query = " Select * From " + table;
In order to use Where
condition do like below., 为了使用Where
条件,如下所示。,
//Where clause only needs single quotes, to define the SQL parameter value in between...
string query = " Select * From " + table + " Where CityId = '" + cityId + "'";
Hope this helps., 希望这可以帮助。,
Best-Practice should be not to do this , because it's susceptible to malicious SQL injection. 最佳实践应该不是这样做 ,因为它容易受到恶意SQL注入。
Anyway, if you have control over the table
variable, you should do it as @madcow69 suggested, but I suggest to add the delimiters, so you always have a valid delimited identifier (for example if your table name is "order" or any other SQL reserved word). 无论如何,如果你可以控制table
变量,你应该像@ madcow69建议的那样,但我建议添加分隔符,所以你总是有一个有效的分隔标识符(例如,如果你的表名是“order”或任何其他SQL保留字)。
string table = "City";
string query = string.format("Select * from [{0}]", table);
But what if table
is the following?: 但如果table
如下呢?:
string table = "City]; DROP DATABASE [YourDB";
You can make it work like this: 你可以让它像这样工作:
string table ="City"
string query = "Select * from "+table;
Hope this helps., 希望这可以帮助。,
string table = "City";
//You don't need to have single quote...
string query = " Select * From " + table;
If you're using .NET4.6
you could use the new "composite string formatting" feature introduced with C# 6.0
(read about it here) . 如果您使用的是.NET4.6
,则可以使用C# 6.0
引入的新“复合字符串格式化”功能(在此处阅读) 。
this enables you to write your statement like this: 这使您可以像这样编写语句:
string query = $"Select * from {table}";
However I would strongly recommend not writing queries like that and use sql parameters . 但是我强烈建议不要编写类似的查询并使用sql参数 。 this will help you avoid SQL Injection attacks . 这将有助于您避免SQL注入攻击 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.