c++中 执行SQL语句

来源:互联网 发布:多线程并发编程问题 编辑:程序博客网 时间:2024/06/06 01:51

网上看的:删除一行数据,虽然下面两个写法都能实现,但是都有问题。

void C数据库测试Dlg::OnBnClickedDelBtn()

{
        int index = m_ListCtrl.GetNextItem(-1, LVNI_SELECTED | LVNI_ALL);
        if (index == -1)
        {
                AfxMessageBox(_T("请选择要删除的项!"));
                return;
        }
        CString str = m_ListCtrl.GetItemText(index, 1);
        strSQL.Format(_T("delete from customerType where ctypeName = '%s'"), str);
        m_pRecordset->Open((_bstr_t)strSQL, m_pConnect.GetInterfacePtr(), adOpenDynamic, adLockOptimistic, adCmdText);
        //        m_pRecordset->Close();   //用上这句后为什么程序崩溃,虽然也能把数据删除!
        OnInitGird();  //再次读取到列表视图控件中
}
为什么加上Close()后程序崩溃,是不是因为Open是打开记录集的函数,但是strSQL语句里是个删除语句,它虽然把这条语句执行了,但是却没有得到记录集,因为它不是select * from,所以得不到查询结果的记录集。如果再关闭的话,程序就崩溃。。不知道这样理解对不对,意思就是说:虽然这用m_pRecordset的Open方法也能实现删除,但是这种方法不对。应该是真正意义上的打开,就是select * from 表,然后再执行添加,删除,修改等。。。。就象下面这样的写法。。。

void C数据库测试Dlg::OnBnClickedDelBtn()
{
        int index = m_ListCtrl.GetNextItem(-1, LVNI_SELECTED | LVNI_ALL);
        if (index == -1)
        {
                AfxMessageBox(_T("请选择要删除的项!"));
                return;
        }
        CString str = m_ListCtrl.GetItemText(index, 1);
        strSQL.Format(_T("select * from customerType"));
        m_pRecordset->Open((_bstr_t)strSQL, m_pConnect.GetInterfacePtr(), adOpenDynamic, adLockOptimistic, adCmdText);
        strSQL.Format(_T("delete from customerType where ctypeName = '%s'"), str);
        m_pConnect->Execute((_bstr_t)strSQL, NULL, adCmdText);
        m_pRecordset->Close();
        OnInitGird();

}

1.

执行update insert delete语句时用m_pConnect->Execute,
因为这些语句不返回数据,只会返回影响的行数.

执行select语句时用m_pRecordset->Open,
也可以用m_pRecordset=m_pConnect->Execute.

2

第一种方法Open函数会执行相应的SQL语句
而你的SQL语句就是删除语句
这个语句会执行但是打开记录集的操作不会成功
再关闭就是会失败了

执行Execute不需要先Open。

0 0
原创粉丝点击