當新的資料錄加入至包含自動編號欄位的 ActiveX 資料物件 (ADO) 資料錄集時,立即報告插入資料錄的 [自動編號] 欄位的值傳回值為 0。
本文將告訴您,如何擷取資料錄插入至 Access 資料庫與 ADO AddNew() 及 Update() 方法的自動編號欄位的自動產生的值。這個範例使用 VBScript 動態伺服器網頁 (ASP) 頁面中。
下列程式碼假設在您電腦上具有 Adventure Works 資料庫,而且您有一個 ODBC 資料來源名稱 (DSN) 名為 AdvWorks 指向它。
這個範例也包括檔案可在 \Program Files\Common Files\System\Ado 中找到的 Adovbs.inc。
這個程式碼不會提示使用者輸入的任何輸入。它 Adventure Works 資料庫的 [客戶] 資料表中插入一筆記錄,並顯示新的資料錄的自動編號欄位 ([客戶編號]) 的值。
以下是要注意的一些關鍵項目:
- [CursorLocation 必須 adUseClient。存取並不支援伺服器端資料指標。
- 為了要填入 [自動編號] 欄位與自動產生的值,必須使用 Requery 方法能查詢資料錄集。
- Requery 方法會將 absolutePosition (書籤) 從新插入的資料錄重設 requeried 資料錄集的第一筆記錄。 如此一來 absolutePosition 必須會呼叫 Requery,之前先儲存並且還原新插入的資料錄,在呼叫 Requery 後。
<%@ Language=VBScript %>
<HTML>
<BODY>
<!--#include file=adovbs.inc -->
<%
Set objConn = CreateObject("ADODB.Connection")
Set objRS = CreateObject("ADODB.Recordset")
objConn.Open "DSN=advworks;"
'Access does not support a cursor engine so a client cursor must be used
objRS.CursorLocation = adUseClient
objRS.Open "SELECT * FROM Customers", objConn, adOpenStatic, adLockOptimistic
' when you invoke the method AddNew it adds a new record to the end of
' your current recordset and places your cursor on that record.
objRS.AddNew
objRS("CompanyName") = "Microsoft"
objRS("ContactFirstName") = "Bob"
objRS("ContactLastName") = "Smith"
objRS.Update
' when you invoke the method Update, it updates the database with the
' values of the new record that we just created. To retrieve the
' value of the Autonumber field we need to update the ADO recordset that
' currently have.
' When you do a Requery on your recordset, you lose your cursor. So
' we need to store the location before we do the Requery, then reset
' it after the Requery.
'before the requery, the Autonumber field shows as 0
Response.Write "<br>ID before Requery = " & objRS("CustomerID")
bookmark = objRS.absolutePosition ' First, store the location of you cursor
objRS.Requery ' Next, update your recordset with the data from the database
'after the requery, the absolutePosition is the first record of the recordset
Response.Write "<br>ID before setting absolutePosition = " & objRS("CustomerID")
objRS.absolutePosition = bookmark ' Finally, change your cursor back
'now we have the Autonumber value
Response.Write "<P>Added ID = " & objRS("CustomerID")
objRS.Close
objConn.Close
set objConn = nothing
set objRS = nothing
%>
</BODY>
</HTML>
如需有關使用 AutoIncrement 欄位和 ADO 的詳細資訊,請參閱 「 Microsoft 知識庫 」 中下列文:
195910?
(http://support.microsoft.com/kb/195910/EN-US/
)
在 ADO 或 RDS 的資訊: 識別 (AutoIncrement) 資料行