我正在从动态生成(尽管经过严格清理)的 SQL 查询过渡到参数化 SQL,并且在变量名方面遇到了一些问题。
我正在使用用 jScript 编码的 Classic ASP。
下面的代码采用评级值 (1-5) 并将其放入数据库中。首先,它会删除用户之前对该对象的所有评分,然后将新评分写入数据库。该函数已经收到并且我已经解析了 Rating 变量(一个 TinyInt)。UserID 和 PgID 值(均为整数)也已发送。
我已经通过用问号替换 @UserID、@PgID 和 @Rating、删除 DECLARE 并将 Append/CreateParemeter 行以正确的顺序放置(每个一个?)来完成这项工作。但是,它确实涉及多次调用 Append/CreateParameter 行(每个 UserID 实例一次),这只是草率。
这段代码不会引发任何错误,但不会向数据库写入任何内容。无论如何,我不知道为什么它可以与问号(和重复的参数)一起使用,但不能与声明的变量一起使用。
在经典 ASP jScript 中使用参数化 SQL 时如何使用命名变量?
如果没有办法做到这一点,有没有办法避免每次我需要重复相同的 Append/CreateParamenter 行,例如,用户 ID?
var sqlReview = "DECLARE @UserID AS Int, @PgID AS Int, @Rating AS TinyInt;"
sqlReview += "DELETE FROM PGrating WHERE (UserID = @UserID) AND (PgID = @PgID);"
sqlReview += "INSERT INTO PGrating (InsertDate, PgID, UserID, Rating) VALUES (GETDATE(), @PgID, @UserID, @Rating);"
var thisConnection = Server.CreateObject("ADODB.Connection");
thisConnection.connectionString = connectString;
thisConnection.Open();
var thisCommand = Server.CreateObject("ADODB.Command");
thisCommand.ActiveConnection = thisConnection;
thisCommand.CommandText = sqlReview;
thisCommand.CommandType = adCmdText;
thisCommand.Parameters.Append(thisCommand.CreateParameter("@UserID", adSmallInt, adParamInput, 2, UserID));
thisCommand.Parameters.Append(thisCommand.CreateParameter("@PgID", adInteger, adParamInput, 4, PgID));
thisCommand.Parameters.Append(thisCommand.CreateParameter("@Rating", adTinyInt, adParamInput, 1, Rating));
var rs = thisCommand.Execute();
thisCommand = null;
thisConnection = null;
我知道可能有更简单的方法可以将评级放入数据库,但创建这个示例主要是因为它很简单,而且我在学习如何使用参数化 SQL 时需要一些简单的东西。在我把它放在这里之前,它也被进一步简化(并再次测试)。一旦我得到这个工作,我就可以构建更复杂的查询。是的,我将编写存储过程,但那是在一切正常之后。