Classic Asp中的参数化查询

时间:2011-10-04 21:48:11

标签: vbscript asp-classic ado

我的数据库访问代码如下:

set recordset = Server.CReateObject("ADODB.Recordset")
set cmd1  = Server.CreateObject("ADODB.Command")
cmd1.ActiveConnection = Conn //connection object already created
cmd1.CommandText = "SELECT * FROM lbr_catmaster where catname = ?"
cmd1.CommandType = adCmdText
set prm = cmd1.CreateParameter("@prm", 200, 1,200 , "development")
cmd1.Parameters.Append prm
set recordset = cmd1.Execute

但是没有数据包命中率。请帮忙。我正在使用sql server 2005。

感谢。

5 个答案:

答案 0 :(得分:3)

在我的代码中,这是我从命令获取记录集的方式:

Set rs = server.createobject("ADODB.Recordset")
Set cmd = server.createobject("ADODB.Command")

cmd.ActiveConnection = Conn //connection object already created
cmd.CommandText = "SELECT * FROM lbr_catmaster where catname = ?"
cmd.CommandType = adCmdText
cmd.CommandTimeout = 900 

set prm = cmd.CreateParameter("@prm", 200, 1, 200, "development")
cmd.Parameters.Append prm

' Execute the query for readonly
rs.CursorLocation = adUseClient
rs.Open cmd, , adOpenForwardOnly, adLockReadOnly

希望有所帮助

答案 1 :(得分:1)

您的查询中似乎没有正确引用您的命名参数。

尝试更换:

cmd1.CommandText = "SELECT * FROM lbr_catmaster where catname = ?"

使用:

cmd1.CommandText = "SELECT * FROM lbr_catmaster where catname = @prm"

看看是否有帮助。

答案 2 :(得分:1)

我喜欢使用Parameters.Refresh,即

set recordset = Server.CReateObject("ADODB.Recordset")
set cmd1  = Server.CreateObject("ADODB.Command")
cmd1.ActiveConnection = Conn //connection object already created
cmd1.CommandText = "SELECT * FROM lbr_catmaster where catname = ?"
cmd1.CommandType = adCmdText
cmd1.Prepared = True ' only needed if u plan to reuse this command often
cmd1.Parameters.Refresh
cmd1.Parameters(0).Value = "development"
set recordset = cmd1.Execute

答案 3 :(得分:0)

尝试不使用参数名称:

set prm = cmd1.CreateParameter(, 200, 1,200 , "development")

答案 4 :(得分:0)

如果您有使用参数的复杂条件,这是我必须根据自己的要求创建的示例

    declare @loc smallint = ? , @dt1 date = ? SET @loc = ISNULL(@loc, 999) 
    SELECT m.* , c.*
    FROM Costs c INNER JOIN MbrData m ON c.SN = m.SN and c.startDT = m.startDT 
    WHERE (m.LocationID = @loc OR @loc = 999) AND (MonthYear = @dt1 OR @dt1 IS NULL) 
    ORDER BY m.LocationID

然后在您的asp中

    cmd.CommandText = strSQL ' the string above
cmd.CommandType = 1 ' adCmdText
cmd.Parameters.Append cmd.CreateParameter("@loc",2,1) 'adSmallInt=2, adParamInput=1
cmd.Parameters("@loc") = rptlocation ' scrubbed location ID
cmd.Parameters.Append cmd.CreateParameter("@dt1",7,1) 'adDate=7, adParamInput=1
cmd.Parameters("@dt1") = scrubbed formatted date
set rst = cmd.Execute