[英]SQL request working fine in SQL Server Management Studio but returning an error when send with sqlCommand C#
I have this statement:我有这样的声明:
SELECT [nozzles].[nozzle_tag],[nozzles].[id]
FROM [dispensers]
INNER JOIN [nozzles]
ON [dispenser_id] = [dispensers].[id]
INNER JOIN (SELECT * FROM assets
WHERE [i4_Device_Name] = 'EH004T_SOURCE2'
AND [i4_site_name] = 'Les Loges - H2e Station (EH004R)')assets
ON [asset_id] = [assets].[id]
WHERE [dispenser_tag] ='Dispenser 2';
It works perfectly fine when I execute it inside SSMS.当我在 SSMS 中执行它时,它工作得很好。
The problem is, when run this SQL by using SQLcommand
, I get an error with this message:问题是,当使用
SQLcommand
运行这个 SQL 时,我收到一条错误消息:
Incorrect syntax near 'Loges'.
“Loges”附近的语法不正确。
I don't understand why.我不明白为什么。
The command above is extracted from a log file, it is exactly what is send using SQLCommand
.上面的命令是从日志文件中提取的,它正是使用
SQLCommand
发送的。
C# code is: C# 代码为:
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(HySoSQLCommandBuilder.GetAllNozzleOfDispenser(locationID, dispenserTag), connection))
{
logger.Info("SQL request {request}", HySoSQLCommandBuilder.GetAllNozzleOfDispenser(locationID, dispenserTag));
using (SqlDataReader reader = command.ExecuteReader())
{
try
{
while (reader.Read())
if (reader.HasRows)
{
list.Add(new nozzle((string)reader["nozzle_tag"], (int)reader["id"]));
}
}
catch { }
}
}
With HySoSQLCommandBuilder.GetAllNozzleOfDispenser()
being fairly straight forward: HySoSQLCommandBuilder.GetAllNozzleOfDispenser()
相当简单:
public static string GetAllNozzleOfDispenser(AssetLocationID assetLocation, string dispenserTag)
{
return $@"SELECT [nozzles].[nozzle_tag],[nozzles].[id]
FROM [dispensers]
INNER JOIN [nozzles]
ON [dispenser_id] = [dispensers].[id]
INNER JOIN (SELECT * FROM assets
WHERE [i4_Device_Name] = '{assetLocation.i4DeviceName}'
AND [i4_site_name] = '{assetLocation.i4SiteName}')assets
ON [asset_id] = [assets].[id]
WHERE [dispenser_tag] ='{dispenserTag}';";
}
None of the injected values are accessible from outside the code.任何注入的值都不能从代码外部访问。 They do not come form a editable field accessible from a user.
它们不是来自用户可访问的可编辑字段。 If SQL injection happens, then that means that it is in the source, done by someone that worked on the code, and can already do whatever they want to the database without the need to encode an SQL injection.
如果发生 SQL 注入,那么这意味着它在源代码中,由编写代码的人完成,并且已经可以对数据库执行任何他们想要的操作,而无需对 SQL 注入进行编码。
changed the code so it uses SQLparameters instead and now it's working.更改了代码,因此它改为使用 SQLparameters,现在它可以工作了。 I don't understand why it wasn't working and that annoy me alot, because fixing an issue without understanding it is not how it should work.
我不明白为什么它不起作用,这让我很恼火,因为在不理解问题的情况下解决问题不是它应该如何工作的。 but at least now it works.
但至少现在它有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.