如何在 Select 语句中插入变量

本文关键字:插入 变量 语句 Select | 更新日期: 2023-09-27 18:23:59

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

这给了我错误,在".

然而

string query = "Select * from City";

提供正确的输出。

如何在 Select 语句中插入变量

你就是这个

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

替换为

string query = "Select * from " + table;

因为查询字符串在形成"Select * from 'City'";时不"Select * from City";

因此你得到错误

最佳做法是使用 string.format

string table = "City";
string query = string.format("Select * from {0}", table);

您需要像下面这样形成查询。

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 + "'"; 

希望这有帮助。

最佳做法应该是不要这样做,因为它容易受到恶意SQL注入的影响。

无论如何,如果你可以控制table变量,你应该按照@madcow69建议进行操作,但我建议添加分隔符,这样你总是有一个有效的分隔标识符(例如,如果你的表名是"order"或任何其他SQL保留字(。

string table = "City";
string query = string.format("Select * from [{0}]", table);

但是,如果table是以下几点呢?

string table = "City]; DROP DATABASE [YourDB";

你可以让它像这样工作:

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

希望这有帮助。

string table = "City";
//You don't need to have single quote...
string query = " Select * From " + table; 
如果您

使用的是.NET4.6则可以使用C# 6.0引入的新"复合字符串格式"功能(在此处
阅读(。这使您能够像这样编写语句:

string query = $"Select * from {table}";

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