往数据表里插入记录后,如何移动记录的指针
往数据表里插入记录后,怎么移动记录的指针?
我有一个按钮,按钮的部分代码是这样的:
strSQL.Format("INSERT INTO student(stu,tel) VALUES ('%s','%s')",m_stuName,m_stuTel);
m_pConnection->Execute((_bstr_t)strSQL,&RecordsAffected,adCmdText);//往数据表里插入一条新记录
try{
m_pRecordset->MoveLast(); //数据表如果是空的,那么程序在这行出错
}
catch(_com_error e){
CString strError;
strError.Format("警告,打开数据表时发生异常。错误信息:%s",e.ErrorMessage());
AfxMessageBox(strError);
return;
}
我的意图是,在插入新记录后,将指针移动到数据表的最后一条记录。
在工程的初始函数OnInitDialog()里,我已经打开了数据表,代码如下:
CString strSQL="SELECT * FROM student";
m_pRecordset->Open(_bstr_t(strSQL),m_pConnection.GetInterfacePtr(),adOpenDynamic,adLockOptimistic,adCmdText);
程序运行后,当数据表里在已经有数据的时候,点击那个按钮,程序正常运行。
但是当数据表是空的、没有记录的时候,点击那个按钮,程序在:m_pRecordset->MoveLast()这里出错
请教出错的原因!谢谢。
------解决方案--------------------
我有一个按钮,按钮的部分代码是这样的:
strSQL.Format("INSERT INTO student(stu,tel) VALUES ('%s','%s')",m_stuName,m_stuTel);
m_pConnection->Execute((_bstr_t)strSQL,&RecordsAffected,adCmdText);//往数据表里插入一条新记录
try{
m_pRecordset->MoveLast(); //数据表如果是空的,那么程序在这行出错
}
catch(_com_error e){
CString strError;
strError.Format("警告,打开数据表时发生异常。错误信息:%s",e.ErrorMessage());
AfxMessageBox(strError);
return;
}
我的意图是,在插入新记录后,将指针移动到数据表的最后一条记录。
在工程的初始函数OnInitDialog()里,我已经打开了数据表,代码如下:
CString strSQL="SELECT * FROM student";
m_pRecordset->Open(_bstr_t(strSQL),m_pConnection.GetInterfacePtr(),adOpenDynamic,adLockOptimistic,adCmdText);
程序运行后,当数据表里在已经有数据的时候,点击那个按钮,程序正常运行。
但是当数据表是空的、没有记录的时候,点击那个按钮,程序在:m_pRecordset->MoveLast()这里出错
请教出错的原因!谢谢。
------解决方案--------------------
- C/C++ code
strSQL.Format("INSERT INTO student(stu,tel) VALUES ('%s','%s')",m_stuName,m_stuTel); m_pConnection->Execute((_bstr_t)strSQL,&RecordsAffected,adCmdText);//往数据表里插入一条新记录 try{ CString strSQL="SELECT * FROM student"; m_pRecordset->Open(_bstr_t(strSQL),m_pConnection.GetInterfacePtr(),adOpenDynamic,adLockOptimistic,adCmdText); if (!m_pRecordset->rsEOF) { //空数据 m_pRecordset->Close(); } else m_pRecordset->MoveLast(); } catch(_com_error e){ CString strError; strError.Format("警告,打开数据表时发生异常。错误信息:%s",e.ErrorMessage()); AfxMessageBox(strError); return; }
------解决方案--------------------
m_pConnection->Execute((_bstr_t)strSQL,&RecordsAffected,adCmdText);//往数据表里插入一条新记录
这一句是直接向数据表里添加记录的,他不会影响已经打开的recordset。
所以如果m_pRecordset第一次open时是空的,此时还是空的,除非你先close再open一次。