如何使用asp从访问数据库中删除特定记录?

时间:2013-07-30 18:37:17

标签: database forms ms-access asp-classic vbscript

所以我有一个名为BrowseAllItems.asp的页面,它显示我的所有数据库信息以及重定向到EditItem.asp(部分显示在下面)的各个编辑按钮,用于编辑或删除该特定记录的数据库信息的选项。编辑数据的部分工作正常,但我可以使用一些帮助删除记录。这就是我所拥有的:

Sub DeleteRecord

ItemCode=request.form("item_code")


'Create an ADO connection object
Dim Connection
Set Connection = Server.CreateObject("ADODB.Connection")

'To open an Access database our string would look like the following:
Dim ConnectionString
ConnectionString = "DRIVER={Microsoft Access Driver (*.mdb)};" &_
                "DBQ=" & Server.MapPath("\") & "\" & FolderName & "\items.mdb;DefaultDir=;UID=;PWD=;"

'Then to open the database we (optionally) set some of the properties of the Connection and call Open
Connection.ConnectionTimeout = 30
Connection.CommandTimeout = 80
Connection.Open ConnectionString

'Create an ADO recordset object
Dim rs
Set rs = Server.CreateObject("ADODB.Recordset")

'Initialise the strSQL variable with an SQL statement to query the database
strSQL = "SELECT * FROM items WHERE ITEM_CODE='" & ItemCode & "' "

我知道它与上面的行有关 - 如果我将“ItemCode”替换为记录的实际项目代码,此代码有效但我需要一种方法从所选记录中获取项目代码并将其应用于它说ItemCode。

rs.LockType = 3
'Open the recordset with the SQL query
rs.Open strSQL, Connection
'Tell the recordset we are deleting a record 
rs.Delete 

rs.Close
'Reset server objects
Set rs = Nothing
Set Connection = Nothing

Response.Write "Record Deleted"

End Sub   

2 个答案:

答案 0 :(得分:2)

也许我误解了一些东西,但看起来像带有参数查询的ADODB.Command在这里很有用。我不明白为什么你需要一个记录集来删除给定ITEM_CODE的记录。

您好像已经有了ADODB.Connection。在本例中,我使用 cnn 而不是 Connection 作为对象变量的名称。

Dim cmd ' As ADODB.Command
Dim lngRecordsAffected ' As Long
strSQL = "PARAMETERS which_item Text(255);" & vbCrLf & _
    "DELETE FROM items WHERE ITEM_CODE = [which_item];"
Set cmd = Server.CreateObject("ADODB.Command")
cmd.CommandType = 1 ' adCmdText
Set cmd.ActiveConnection = cnn
cmd.CommandText = strSQL
'cmd.Parameters.Append cmd.CreateParameter("which_item", _
'    adVarChar, adParamInput, 255, ItemCode)
cmd.Parameters.Append cmd.CreateParameter("which_item", _
    200, 1, 255, ItemCode)
cmd.Execute lngRecordsAffected
Set cmd = Nothing
' lngRecordsAffected is the number of records deleted in case you 
' need it for anything ... perhaps you'd like to do this ...
Response.Write lngRecordsAffected & " Record(s) Deleted"

答案 1 :(得分:0)

在我看来,你正在失去“ItemCode”值。你发布了你的请求吗? request.formpost行为相关。另一方面,request.querystring从查询字符串中收集数据(get操作),request("ItemCode")捕获这两种情况。

在任何情况下you must sanitize!!! before a concatenation为了防止SQL注入,在你的情况下,认为ItemCode是一个整数,你可以像这样使用cint

ItemCode = cint(request("item_code"))

我猜你的查询不会抛出错误,因为单引号的存在,其值为“ItemCode”的空值给出了一个不返回数据的有效SQL语句。在调试时,您可以始终response.write strSQL执行(或打开)句子。

相关问题