码迷,mamicode.com
首页 > 数据库 > 详细

sqlite3使用事务处理[zz]

时间:2014-08-04 17:07:57      阅读:271      评论:0      收藏:0      [点我收藏+]

标签:style   使用   os   io   文件   数据   for   问题   

<!-- /* Font Definitions */ @font-face {font-family:宋体; panose-1:2 1 6 0 3 1 1 1 1 1; mso-font-alt:SimSun; mso-font-charset:134; mso-generic-font-family:auto; mso-font-pitch:variable; mso-font-signature:3 135135232 16 0 262145 0;} @font-face {font-family:Verdana; panose-1:2 11 6 4 3 5 4 4 2 4; mso-font-charset:0; mso-generic-font-family:swiss; mso-font-pitch:variable; mso-font-signature:536871559 0 0 0 415 0;} @font-face {font-family:"/@宋体"; panose-1:2 1 6 0 3 1 1 1 1 1; mso-font-charset:134; mso-generic-font-family:auto; mso-font-pitch:variable; mso-font-signature:3 135135232 16 0 262145 0;} /* Style Definitions */ p.MsoNormal, li.MsoNormal, div.MsoNormal {mso-style-parent:""; margin:0cm; margin-bottom:.0001pt; text-align:justify; text-justify:inter-ideograph; mso-pagination:none; font-size:10.5pt; mso-bidi-font-size:12.0pt; font-family:"Times New Roman"; mso-fareast-font-family:宋体; mso-font-kerning:1.0pt;} /* Page Definitions */ @page {mso-page-border-surround-header:no; mso-page-border-surround-footer:no;} @page Section1 {size:595.3pt 841.9pt; margin:72.0pt 90.0pt 72.0pt 90.0pt; mso-header-margin:42.55pt; mso-footer-margin:49.6pt; mso-paper-source:0; layout-grid:15.6pt;} div.Section1 {page:Section1;} -->

在对 sqlite3 insert into 等操作时速度比较慢。

原因:它以文件的形式存在磁盘中,每次访问时都要打开一次文件,如果对数据库进行大量的操作,就很慢。

解决办法:用事物的形式提交,因为开始事务后,进行的大量操作语句都保存在内存中,当提交时才全部写入数据库,此时,数据库文件也只用打开一次。如果操作错误,还可以回滚事务。

接口:事务的操作没有特别的接口函数,就是一个普通的 sql 语句而已,分别如下:

 

int ret ;
ret = sqlite3_exec ( db , "begin transaction" , 0 , 0 , & zErrorMsg ); // 开始一个事务

ret = sqlite3_exec ( db , "commit transaction" , 0 , 0 , & zErrorMsg ); // 提交事务

ret = sqlite3_exec ( db , "rollback transaction" , 0 , 0 , & zErrorMsg );


例程:在进行大量的操作前使用如下语句

ret = sqlite3_exec ( db , "begin transaction" , 0 , 0 ,& zErrorMsg );
for (...)
{
  //insert into operate

 
  // 如果操作错误

 ret = sqlite3_exec ( db , "rollback transaction" , 0 , 0 , & zErrorMsg )
}
ret = sqlite3_exec ( db , "commit transaction" , 0 , 0 , & zErrorMsg );

 

开发过程遇到这样的问题:

分别对两个数据库文件的不同表进行操作,执行顺序为: open db A->begin trasaction->open db B->select from db B->close db B->select from db A->rollbak or commit->close db A

测试发现, select from db B 这一步会出错,错误信息为library routine called out of sequence ,出错后执行 rollback ,这一步也会报错。

原来以为原因是:开始一个事务只能对一个数据库进行操作。

测试发现,即使不开始事务,执行顺序为: open db A->open db B->select from db B->close db B->select from db A->close db A , 仍会出现ibrary routine called out of sequence 的错误。

难道打开一个数据库,在关闭其之前不能打开其他数据库?

难道sqlite 的并发执行需要用户自己来控制?

 

今天发现,以上出错原因可能是总控程序和子程序的全局变量一致(都是sqlite3 *db ),导致总控程序的全局变量被修改。

具体还需进一步研究。

sqlite3使用事务处理[zz],布布扣,bubuko.com

sqlite3使用事务处理[zz]

标签:style   使用   os   io   文件   数据   for   问题   

原文地址:http://www.cnblogs.com/ejllen/p/3890238.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!