我们如何使用 CRecordset 批量更新记录

Posted

技术标签:

【中文标题】我们如何使用 CRecordset 批量更新记录【英文标题】:How can we bulk update records using CRecordset 【发布时间】:2012-02-02 17:21:33 【问题描述】:

我有一个 mfc 应用程序,它使用 CRecordsets 来获取和更新/插入数据。

我能够实现批量行获取,但我现在希望使用派生的 CRecordset 实现批量行更新/插入/删除。

有人做过吗?能否提供代码示例?

【问题讨论】:

您批量获取哪些数据类型? 我需要能够获取几乎所有类型:bool byte short long float double binary text guid... 所以批量获取文本对您有用吗?我问是因为我有this problem。 【参考方案1】:

我偶然发现了一篇描述如何在 CRecordset 上实现批量行更新的旧帖子。 首先,你必须在你的记录集上实现bulk row fetching(你也可以看到this post的例子)

一旦您的记录集用于获取数据,就非常简单了。

//Declare your recordset
CMyRecordsetBulk regSetBulk(&myDatabase);

//Open it
regSetBulk.Open(NULL, NULL, CRecordset::useMultiRowFetch);

//Select the row you want to change
regSetBulk.SetRowsetCursorPosition(nRow);

//Update the value(s) you need to change.
regSetBulk.m_pnPrecision = 21;

//Set the length of the data in the field you modified (the "Precision" field is a byte)
regSetBulk.m_plnPrecision = 1;


//Do the same thing for a couple of other rows

regSetBulk.SetRowsetCursorPosition(++nRow);
regSetBulk.m_pnPrecision = 32;
regSetBulk.m_plnPrecision = 1;

regSetBulk.SetRowsetCursorPosition(++nRow);
regSetBulk.m_pnPrecision = 21;
regSetBulk.m_plnPrecision = 1;

regSetBulk.SetRowsetCursorPosition(++nRow);
regSetBulk.m_pnPrecision = 12;
regSetBulk.m_plnPrecision = 1;

//Update the rows and check for errors
int nRetCode;
AFX_ODBC_CALL(::SQLSetPos(regSetBulk.m_hstmt, NULL, SQL_UPDATE, SQL_LOCK_NO_CHANGE)); 
regSetBulk.CheckRowsetError(nRetCode);

【讨论】:

【参考方案2】:

只需使用CDatabase::ExecuteSQL。通过循环作为 CRecordset 进行更新并不是您真正想做的事情。 CRecordSet 仅在您使用单个条目而不是整组数据时才有用。

【讨论】:

其实使用CRecordset插入数据一般比使用CDatabase::ExecuteSQL要快。我最近遇到了一个 msAccess 案例,其中使用 CRecordset 而不是 ExecuteSQL 将插入时间从 40 秒减少到 3 秒。 调试/进入记录集类,看看它做了什么:创建一个 sql 语句并执行它! 比这更复杂。 CRecordset 类做变量和参数绑定等可以加快处理速度的东西。 但是谁说你一次只能执行一个 INSERT?!创建大量它们并且只执行一次,您将节省大量的 db-roundtrips! 你会怎么做呢? CDatabase::ExecuteSQL 一次只执行一条语句

以上是关于我们如何使用 CRecordset 批量更新记录的主要内容,如果未能解决你的问题,请参考以下文章

更新数据库 MFC C++ ODBC CRecordset

线程安全地构造 C++ 对象(MFC CRecordset)

如何使用 C#/SQL 批量更新 1000 条记录

CRecordset 返回定位请求无法执行

mysql进阶 十四 批量更新与批量更新多条记录的不同值实现方法

mysql 批量更新与批量更新多条记录的不同值实现方法