我正在從動態生成的SQL查詢過渡到參數化的SQL,而且我遇到了一些變量名稱的問題。在經典ASP中使用變量參數化SQL
我使用的是經典的ASP,使用jScript編碼。
下面的代碼將評分值(1-5)取出並放入數據庫中。首先刪除用戶對該對象的所有先前評級,然後將新評級寫入數據庫。該函數已經收到,我已經解析了Rating變量(一個TinyInt)。 UserID和PgID值(都是整數)也被髮送。
我已經通過用問號替換@UserID,@PgID和@Rating,刪除DECLAREs,並將Append/CreateParemeter行按照正確的順序(每個一個?)置換來工作。它確實涉及多次調用Append/CreateParameter行(對於每個UserID實例一次),這只是馬虎。
這段代碼不會拋出任何錯誤,但它不會寫入任何數據。 無論如何,我不知道爲什麼它會適用於問號(和重複參數),但不適用於聲明的變量。
如何在經典ASP jScript中使用參數化SQL時使用命名變量?
如果沒有辦法做到這一點,有沒有辦法避免每次需要重複相同的Append/CreateParamenter行,例如UserID?
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。在我把它放在這裏之前,它還被進一步簡化(並再次測試)。一旦我得到這個工作,我可以構建更復雜的查詢。是的,我會編寫存儲過程,但後來發生,一切正常。
您的問題是什麼? – Oded 2011-06-16 19:18:34
如何在Classic ASP jScript中創建參數化SQL調用時使用命名變量? (現在添加到上面的問題)......如果沒有辦法,是否有一種方法可以避免每次需要時添加/ CreateParamenter,例如UserID? – 2011-06-16 20:06:17