这样读取结果集会出现问题
/**********************数据库操作*******************/
int MonitorNum::sql_insert(void)
{
//将当前的对象插入表中,请用户自己保证当前的数据成员有效
//连接数据库
ADOConn m_AdoConn;
m_AdoConn.OnInitADOConn();
int iRst = 0;
//读取当前最大编号
int iId;
_bstr_t vSQL;
vSQL = "select max(id_monitor) as MaxId from monitor_number_table";
_RecordsetPtr m_pRecordset;
m_pRecordset = m_AdoConn.GetRecordSet(vSQL);
if(m_pRecordset->rsEOF)
{
//说明表中没有数据
iId = 0;
}
else
{
iId = m_pRecordset->GetCollect("MaxId");
}
//将新数据插入表中,成为最大编号
m_id_monitor = iId + 1;
iRst = iId + 1;
CString strSql;
strSql.Format("insert into monitor_number_table(id_monitor, number_monitor, threshold_monitor, warn_counts) \
values(%d, '%s', %d, %d)", m_id_monitor, m_num_monitor, m_threshold, m_warn_counts);
if(FALSE == m_AdoConn.ExecuteSQL((_bstr_t)strSql))
{
iRst = -1;
}
//关闭连接
m_AdoConn.ExitConnect();
//返回当前最大编号
return iRst;
}
iId = m_pRecordset->GetCollect("MaxId"); //现象:当表为空的时候,rsEOF不为真,进入else分支,此时无法读取结果集
解决办法有以下两种:
/**********************数据库操作*******************/
int ReceiverNum::sql_insert(void)
{
//将当前的对象插入表中,请用户自己保证当前的数据成员有效
//连接数据库
ADOConn m_AdoConn;
m_AdoConn.OnInitADOConn();
//读取当前最大编号
int iId = 0;
CString strSql;
_RecordsetPtr m_pRecordset;
#if 0
<span style="color:#ff6666;">//先判断下是否是空表,空表会导致下面语句失败
//iId = _ttoi((LPCTSTR)(_bstr_t)(m_pRecordset->GetCollect("MaxId")));</span>
strSql.Format("select * from receiver_number_table");
TRACE(strSql + "\n");
m_pRecordset = m_AdoConn.GetRecordSet((_bstr_t)strSql);
if(m_pRecordset->rsEOF)
{
TRACE("if id = %d\n", iId);
//说明表中还没有数据
iId = 0;
}
else
{
strSql.Format("select max(id_receiver) as MaxId from receiver_number_table");
TRACE(strSql + "\n");
m_pRecordset = m_AdoConn.GetRecordSet((_bstr_t)strSql);
TRACE("iId = %d\n", iId);
iId = _ttoi((LPCTSTR)(_bstr_t)(m_pRecordset->GetCollect("MaxId")));
TRACE("iId = %d\n", iId);
}
#else
<span style="white-space:pre"> </span>
<span style="color:#ff6666;">strSql.Format("select * from receiver_number_table where id_receiver = (select max(id_receiver) from receiver_number_table)");</span>
TRACE(strSql + "\n");
m_pRecordset = m_AdoConn.GetRecordSet((_bstr_t)strSql);
if(m_pRecordset->rsEOF)
{
TRACE("if id = %d\n", iId);
//说明表中还没有数据
iId = 0;
}
else
{
TRACE("iId = %d\n", iId);
iId = _ttoi((LPCTSTR)(_bstr_t)(m_pRecordset->GetCollect("id_receiver")));
TRACE("iId = %d\n", iId);
}
#endif
//将新数据插入表中,成为最大编号
m_id_receiver = iId + 1;
strSql.Format("insert into receiver_number_table(id_receiver, number_receiver, send_counts) \
values(%d, '%s', %d)", m_id_receiver, m_num_receiver, m_send_counts);
TRACE(strSql +"\n");
if(!m_AdoConn.ExecuteSQL((_bstr_t)strSql))
{
AfxMessageBox("新增接收号码失败!");
}
//关闭连接
m_AdoConn.ExitConnect();
//返回当前最大编号
return (iId + 1);
}