如何在Select语句中插入变量

6
string table = "City";
string query = "Select * from '"+table+"'";

这让我出现了错误,指出在“.”附近有不正确的符号。

然而,

string query = "Select * from City";

给出正确的输出。

使用 [ ] 替换单引号,它应该能够正常工作。 - dawncode
你有检查查询输出吗?你可以尝试这个 - string query = "Select * from "+table; - Abhash Upadhyaya
1
查询 = "选择 * 从 " + 表格; 但请相信我,如果您的表格变量不是一个字面字符串,这是不安全的。不要将来自任何来源的输入连接起来构建SQL语句。 - Oguz Ozgul
7个回答

5
你只需要这样做。
string query = "Select * from '"+table+"'";

将被替换为

string query = "Select * from " + table;

由于您的查询字符串不是 "Select * from City"; 而是 "Select * from 'City'";,因此您遇到了错误。


3
最佳实践是使用 string.format。
string table = "City";
string query = string.format("Select * from {0}", table);

2
你需要按以下方式形成查询。
string table = "City";

//You don't need to have single quote...

string query = " Select * From " + table; 

为了使用Where条件,请按照以下方式进行操作。
//Where clause only needs single quotes, to define the SQL parameter value in between...

string query = " Select * From " + table + " Where CityId = '" + cityId + "'"; 

希望这可以帮助你。

1
最佳实践应该不要这样做,因为它容易受到恶意SQL注入攻击的影响。
无论如何,如果您对table变量有控制权,您应该按照@madcow69的建议进行操作,但我建议添加分隔符,这样您始终具有有效的分隔标识符(例如,如果您的表名是“order”或任何其他SQL保留字)。
string table = "City";
string query = string.format("Select * from [{0}]", table);

那么如果表格(table)是以下内容呢?
string table = "City]; DROP DATABASE [YourDB";

0
你可以这样让它工作:
string table ="City"
string query = "Select * from "+table;

@subhro,如果这个答案对您有用,请接受它。 - Abhash Upadhyaya

0
希望这能有所帮助。
string table = "City";

//You don't need to have single quote...

string query = " Select * From " + table; 

0
如果您正在使用.NET4.6,您可以使用引入于C# 6.0的新的“组合字符串格式化”功能(在此处阅读有关此功能的信息)。这使您可以像这样编写语句:
string query = $"Select * from {table}";

然而,我强烈建议不要编写那样的查询语句,而是使用SQL参数。这将帮助您避免SQL注入攻击


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接