数据库菜鸟问题, 请问怎么样可以向数据库刚插入一条记录后, 就得到该条记录的索引ID.

dash 2003-08-02 09:38:05
我不太懂数据库,我现在只能插入记录后,再用一条SQL语句把新记录
的ID再给查出来,觉得烦,而且应该有更好的方法的.请问能不能插入的时候
就返回该记录的ID啊?
谢谢
...全文
74 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
dash 2003-08-02
  • 打赏
  • 举报
回复
哦, 是这样啊.

谢谢.给分.
masterz 2003-08-02
  • 打赏
  • 举报
回复
select 语句会返回记录集,insert into不会返回记录集
dash 2003-08-02
  • 打赏
  • 举报
回复
不好意思,没有马上回复,太热洗澡去了.
我照着你给的代码, 象这样做为什么不行呢?我的m_pRecordSet也是_RecordsetPtr,
按我的理解,m_pRecordset也应该是新插入的记录啊.为什么TRACE就错了.

m_pCommand->CommandText = "insert into Device (EntryIP,IsRouter) Values ('127.0.0.10','1')";
m_pRecordset = m_pCommand->Execute(NULL, NULL,adCmdText);
TRACE("AutoID is %d",(long)(m_pRecordset->Fields->Item["ID"]->Value));

主要是按照你给的代码改,改动太大了. :)
masterz 2003-08-02
  • 打赏
  • 举报
回复
设bookmark没有成功,不设它照样去出来了,意料之外
// mdbautoid.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "stdio.h"
#include <tchar.h>
#import "e:\Program Files\Common Files\System\ado\msado15.dll"\
no_namespace rename("EOF", "EndOfFile")
int main(int argc, char* argv[])
{
TCHAR conn_str_buf[1024];
LPCTSTR db_path=_T("C:\\temp\\test.mdb");
wsprintf(conn_str_buf,"PROVIDER=MSDASQL;DRIVER="
"{Microsoft Access Driver (*.mdb)};DBQ=%s;UID=;PWD=;",db_path);
CoInitialize(NULL);
try
{
_ConnectionPtr pConn("ADODB.Connection");
_RecordsetPtr pRst("ADODB.Recordset");
pConn->Open(conn_str_buf,"","",adConnectUnspecified);
pRst->Open("table1", _variant_t((IDispatch *) pConn, true),
adOpenKeyset, adLockOptimistic, adCmdTable);
FieldsPtr fds=pRst->GetFields();
printf("printf field name of the table\n");
for(int i=0;i<fds->GetCount();i++)
{
FieldPtr fd=fds->GetItem(_variant_t(short(i)));
printf("%s ",(LPCTSTR)fd->GetName());
}
//_variant_t vBookMark = pRst->Bookmark;
pRst->AddNew();
pRst->Fields->Item["data"]->Value = (long)123456;
pRst->Update();
//pRst->MoveFirst();
//pRst->Bookmark = vBookMark;
printf("AutoID is %d",(long)(pRst->Fields->Item["testid"]->Value));
pRst->MoveFirst();

pRst->Close();
pConn->Close();
}
catch (_com_error &e)
{
printf("Description = '%s'\n", (char*) e.Description());
}
::CoUninitialize();
return 0;
}
dash 2003-08-02
  • 打赏
  • 举报
回复
不是sql server,是access,自己写的小应用.
dash 2003-08-02
  • 打赏
  • 举报
回复
to masterz:
老实说,不太懂.那个"bookmark"是什么东西? 能不能稍微写两行代码.
我现在的代码基本是这样的.
m_pCommand->CommandText = "Insert .....";
m_pRecordset = m_pCommand->Execute(NULL, NULL,adCmdText);
small_wei 2003-08-02
  • 打赏
  • 举报
回复
是sql server的话用 select @@IDENTITY as id
jounercool 2003-08-02
  • 打赏
  • 举报
回复
同意楼上大虾的话+佩服呵呵

不过我是来接分的拉

谢谢拉先
masterz 2003-08-02
  • 打赏
  • 举报
回复
先得到这条记录的bookmark,update之后再设定这个bookmark,取得他的id

4,011

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC 数据库
社区管理员
  • 数据库
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧