我不太懂数据库,我现在只能插入记录后,再用一条SQL语句把新记录
的ID再给查出来,觉得烦,而且应该有更好的方法的.请问能不能插入的时候
就返回该记录的ID啊?
    谢谢

解决方案 »

  1.   

    先得到这条记录的book,update之后再设定这个book,取得他的id
      

  2.   

    是sql server的话用 select @@IDENTITY as id
      

  3.   

    to masterz:
      老实说,不太懂.那个"book"是什么东西? 能不能稍微写两行代码.
    我现在的代码基本是这样的.
    m_pCommand->CommandText = "Insert .....";  
    m_pRecordset = m_pCommand->Execute(NULL, NULL,adCmdText);
      

  4.   

    不是sql server,是access,自己写的小应用.
      

  5.   

    设book没有成功,不设它照样去出来了,意料之外
    // 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->Book;
    pRst->AddNew();
    pRst->Fields->Item["data"]->Value = (long)123456;
    pRst->Update();
    //pRst->MoveFirst();
    //pRst->Book = 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;
    }
      

  6.   

    不好意思,没有马上回复,太热洗澡去了.
    我照着你给的代码, 象这样做为什么不行呢?我的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));主要是按照你给的代码改,改动太大了.   :)
      

  7.   

    select 语句会返回记录集,insert into不会返回记录集