How to use last_insert_id() with “ADODB.Connection

2019-09-10 17:25发布

问题:

I'm having a problem in retrieving last record id from database. This code below, is the closer I can get. But still, it return record id, as 0; ,then when I execute again, it will return, record of previous execute, not the current one.

sql = "insert into program (prog_det,budget,prog_obj,outcome,target_group,awareness,engagement,issue,seq_no) value ('"&prog_title&"','"&prog_budget&"','"&prog_obj&"','"&prog_result&"','"&prog_target&"','"&prog_aware&"','"&prog_involment&"','"&prog_issues&"','99');"

sql2 = "select last_insert_id() as last_id"

set kpi_prog_conn=Server.CreateObject("ADODB.Connection")
set kpi_prog_rs=Server.CreateObject("ADODB.Recordset")

kpi_prog_conn.Open ObjConn
kpi_prog_conn.Execute(sql)

kpi_prog_conn.Open sql2,objConn,adLockPessimistic

response.write kpi_prog_rs("last_id")

回答1:

Your penultimate line looks wrong

Try

kpi_prog_rs.Open sql2,kpi_prog_conn,adLockPessimistic


回答2:

IS the ID you are trying to retrieve is the Primary key of the corresponding table? Try using Scope_Identity() instead of last_insert_id()

Query - SELECT SCOPE_IDENTITY() AS [LAST_IDENTITY]

It returns you the last inserted id into the table



回答3:

I don't have mysql but try:

sql2 = "select last_insert_id() as last_id;"
sql = "insert into program (prog_det,budget,prog_obj,outcome,target_group,awareness,engagement,issue,seq_no) value ('"&prog_title&"','"&prog_budget&"','"&prog_obj&"','"&prog_result&"','"&prog_target&"','"&prog_aware&"','"&prog_involment&"','"&prog_issues&"','99');" & sql2
set kpi_prog_conn=Server.CreateObject("ADODB.Connection")
kpi_prog_conn.Open ObjConn
set kpi_prog_rs = kpi_prog_conn.Execute(sql)
anotherRecordset = kpi_prog_rs.NextRecordset
response.write anotherRecordset("last_id")