我正在尝试构建一个 SQL 查询并将一个字符串作为参数传递。但是,我遇到了不正确的语法错误。我已经打印出这些值,但对我来说一切都很好。
我有一个字符串“sqlString”,它是通过一系列连接构建的,产生这个:
sqlString = " and (event_id=60 OR event_id=61 OR event_id=56 OR event_id=73)"
SqlCommand totalCmd = new SqlCommand();
totalCmd.CommandText = "SELECT sum(datediff(hour,[event_start],[event_end])) as Timeworked FROM event WHERE (event_start >= @StartDate and event_end <= @EndDate) @mySqlString";
totalCmd.Parameters.AddWithValue("StartDate", txtStartDate.Text);
totalCmd.Parameters.AddWithValue("EndDate", txtEndDate.Text);
totalCmd.Parameters.AddWithValue("mySqlString", sqlString);
totalDT = SqlComm.SqlDataTable(totalCmd);
这是一个错误
Incorrect syntax near '@mySqlString'
我通过输入参数直接在 SQL 中运行了这个查询,它运行良好。传递 mySqlString
参数有什么问题?
最佳答案
您不能将 sqlString
添加为参数。您应该将其直接连接到 CommandText:
totalCmd.CommandText = "SELECT sum(datediff(hour,[event_start],[event_end])) as Timeworked FROM event WHERE (event_start >= @StartDate and event_end <= @EndDate) " + sqlString;
向 Parameters
添加值而不是串联的全部意义(除了整洁之外)是清除恶意命令的值 - 即参数应该只是纯值。所以按照您现在的方式,sqlString
被解释为 SQL injection攻击,并且基本上会被该检查清除。
关于c# - SQL CommandText 语法不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20575372/