简单的 SQL 语法问题
本文关键字:问题 语法 SQL 简单 | 更新日期: 2023-09-27 17:56:43
我的查询似乎在我的代码中没有响应,但是,在SQL脚本区域中,我的脚本干净地执行。 手头的问题必须只是我从查询的其余部分插入变量的方式,例如在末尾添加括号但未被读取。我在 .NET 网格视图中执行此操作。任何想法将不胜感激。 如果您需要更多信息,请告诉我。
SQL(没有问题):
SELECT [TeamID], [TeamName], [SportsType], [ContactName], [ContactPhone], [ContactEmail] FROM [Teams] WHERE CompanyID = (SELECT CompanyID FROM Company WHERE companyadminUserName = 'rec1') OR CompanyID = (SELECT CompanyID FROM Employee WHERE EmployeeBarcodeNumber = 'rec1')
在代码(问题)中:
public String loggedInUser = "rec1";
SqlDataSource1.SelectCommand = "SELECT [TeamID], [TeamName], [SportsType], [ContactName], [ContactPhone], [ContactEmail] FROM [Teams] WHERE CompanyID = (SELECT CompanyID FROM Company WHERE companyadminUserName ="+loggedInUser+") OR CompanyID = (SELECT CompanyID FROM Employee WHERE EmployeeBarcodeNumber ="+loggedInUser+"')'";
连接
这样的查询可能是一个非常糟糕的安全漏洞。如果要编写生产代码,请使用 SqlParameters 来防止 SQL 注入攻击。使用 SqlParameters 还意味着您遇到与报价相关的错误(例如您拥有的错误)的机会较小。
SQLParameter如何防止SQL注入?
SqlCommand sqlCmd =
@"SELECT
[TeamID],
[TeamName],
[SportsType],
[ContactName],
[ContactPhone],
[ContactEmail]
FROM [Teams]
WHERE CompanyID = (
SELECT CompanyID
FROM Company
WHERE companyadminUserName = @loggedInUser
)
OR CompanyID = (
SELECT CompanyID
FROM Employee
WHERE EmployeeBarcodeNumber = @loggedInUser
)";
sqlCmd.Parameters.Add(new SqlParameter("@loggedInUser", SqlDbType.NVarChar) { Value = loggedInUser });
在代码中构建查询时,您似乎缺少一些" ' "。
试试这个:
public String loggedInUser = "rec1";
SqlDataSource1.SelectCommand = "SELECT [TeamID], [TeamName], [SportsType], [ContactName], [ContactPhone], [ContactEmail] FROM [Teams] WHERE CompanyID = (SELECT CompanyID FROM Company WHERE companyadminUserName = '"+loggedInUser+"') OR CompanyID = (SELECT CompanyID FROM Employee WHERE EmployeeBarcodeNumber = '"+loggedInUser+"')";
你的 sql 命令字符串有问题
SqlDataSource1.SelectCommand = "SELECT [TeamID], [TeamName], [SportsType], [ContactName], [ContactPhone], [ContactEmail] FROM [Teams] WHERE CompanyID = (SELECT CompanyID FROM Company WHERE companyadminUserName = '"+loggedInUser+"') OR CompanyID = (SELECT CompanyID FROM Employee WHERE EmployeeBarcodeNumber = '"+loggedInUser+"')";
u 应该在登录的用户中添加 ''