Parameterized query in Classic Asp

前端 未结 5 763
小鲜肉
小鲜肉 2020-11-29 13:56

My db access code is like following:

set recordset = Server.CReateObject(\"ADODB.Recordset\")
set cmd1  = Server.CreateObject(\"ADODB.Command\")
cmd1.ActiveC         


        
相关标签:
5条回答
  • 2020-11-29 14:04

    In my code, this is how I get a recordset from a command:

    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
    

    Hope it helps

    0 讨论(0)
  • 2020-11-29 14:10

    Looks like you aren't referencing your named parameter correctly in your query.

    Try replacing:

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

    with:

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

    and see if that helps.

    0 讨论(0)
  • 2020-11-29 14:11

    If you have a complex criteria using parameters here is an example I had to create based on my requirements

        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
    

    then in your 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
    
    0 讨论(0)
  • 2020-11-29 14:13

    I like using Parameters.Refresh, i.e.

    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
    
    0 讨论(0)
  • 2020-11-29 14:23

    Try leaving off the parameter name:

    set prm = cmd1.CreateParameter(, 200, 1,200 , "development")
    
    0 讨论(0)
提交回复
热议问题