Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the insert ID from this ADODB.Recordset?

I'm trying to avoid using straight SQL queries in my web app. I looked around and have come to the conclusion that ADO Recordsets would be the best or at least safest tool for the job. I need to insert records into a database table. Unfortunately I'm at a loss as to how to get the identity value for the record which was just inserted. Here's a reduction of what I've got now:

<%
dim insertID, rs
set rs = Server.CreateObject("ADODB.Recordset")
rs.Open "my_table_name", conn, adOpenForwardOnly, adLockOptimistic

rs.AddNew()

Call m_map_values_to_rs(rs)

rs.Update()

insertID = rs("id")

rs.Close()
rs = Nothing
%>

The code I have is successfully inserting the record, but I can't for the life of me figure out how to get the id field of the Recordset to update after the insert. How can I get the identity column value back from this Recordset?

UPDATE - Here's the solution with regard to the code above.

I had to change the cursor type to adOpenKeyset instead of adOpenForwardOnly. After I did this the record is automatically updated with the "auto number" field's new value after the insert. However it is not what you think it is. The value of rs("id") doesn't become an integer or even a variant. It becomes some sort of Automation type and cannot be evaluated as a number. Nor can CInt() be used directly on that type for some reason. So what you must do is to convert the value to a string and then convert it to an Int. Here's how I managed that:

insertID = CInt( rs("id") & "" )

Thanks to Dee for their answer. It helped immensely.

like image 756
sholsinger Avatar asked Mar 31 '11 21:03

sholsinger


People also ask

What is Adodb recordset?

An ADODB Recordset in VBA is a storage item: you can store all kinds of different things in it: numbers, texts, dates. An ADODB Recordset is a database that you can design, fill and edit completely in the working memory. VBA has several other options for storing data: - a dictionary. - a collection.

What is recordset in Javascript?

The ADO Recordset object is used to hold a set of records from a database table. A Recordset object consist of records and columns (fields). In ADO, this object is the most important and the one used most often to manipulate data from a database.


1 Answers

This article explains the means of getting identity value with example code.

The relevant code snippet is:

<% 
    fakeValue = 5 
    set conn = CreateObject("ADODB.Connection") 
    conn.open "<conn string>" 
    sql = "INSERT someTable(IntColumn) values(" & fakeValue & ")" & _ 
        VBCrLf & " SELECT @@IDENTITY" 
    set rs = conn.execute(sql) 
    response.write "New ID was " & rs(0) 
    rs.close: set rs = nothing 
    conn.close: set conn = nothing 
%>
like image 196
Dee Avatar answered Sep 18 '22 18:09

Dee