How to use last_insert_id() with “ADODB.Connection

2019-09-10 17:36发布

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")

3条回答
该账号已被封号
2楼-- · 2019-09-10 17:58

Your penultimate line looks wrong

Try

kpi_prog_rs.Open sql2,kpi_prog_conn,adLockPessimistic
查看更多
Juvenile、少年°
3楼-- · 2019-09-10 18:06

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

查看更多
我只想做你的唯一
4楼-- · 2019-09-10 18:12

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")
查看更多
登录 后发表回答