sqlite3x 的基本用法

前端之家收集整理的这篇文章主要介绍了sqlite3x 的基本用法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

sqlite3x的基本用法

  1. #include <string>
  2. #include <iostream>
  3. #include <stdexcept>
  4. #include "constant.h"
  5. #include <time.h>
  6. #include "sqlite3x/sqlite3x.hpp"
  7.  
  8. using namespace std;
  9. using namespace sqlite3x;
  10.  
  11. int main(void) {
  12. try {
  13. /*
  14. 打开一个数据库连接,只需创建一个sqlite3_connection对象指定要连接的数
  15. 据库,如果数据不存在创建这个数据库
  16. */
  17. sqlite3_connection con("test.db");
  18. /*
  19. 执行一条sql语句,查询当前系统是否存在表名为’t_test’的表
  20. 直接调用sqlite3_connection的方法可以执行语句,并根据语句类型返回不同类型的值,
  21. 当然需要调用不同的方法,比如返回一个string型的值可以调用con.executestring()方法
  22. */
  23. int count=con.executeint("select count(*) from sqlite_master where name='t_test';");
  24. if(count==0)
  25. {
  26. /*
  27. 创建数据表:t_test,包含两个字段。
  28. */
  29. con.executenonquery("create table t_test(number,string);");
  30. }
  31. //为了测试使用和不使用事务的时候效率的区别
  32. time_t begin,end;
  33. begin = time(NULL);
  34. /*
  35. 使用事务执行语句
  36. */
  37. sqlite3_transaction trans(con);
  38. {
  39. /*
  40. 创建sqlite3_command对象来执行语句,对于需要给定参数的地方,可以在语句上写“?”,在用bind()方法来给定参数的实际值。
  41. */
  42. sqlite3_command cmd(con,"insert into t_test values(?,?);");
  43. //cmd.bind(2,"foobar",6);
  44. std::string ff("foobar");
  45. for(int i=0; i<10; i++) {
  46. cmd.bind(2,ff);
  47. cmd.bind(1,(int)i);
  48. cmd.executenonquery();
  49. }
  50. }
  51. trans.commit();
  52. end = time(NULL);
  53. cout<<"time"<<end-begin<<endl;
  54.  
  55.  
  56.  
  57. //selete
  58. // sqlite3_command cmd(con,"select number,string from t_test where number = ?;");
  59. sqlite3_command cmd1(con,"select* from t_test ;");
  60. // cmd.bind(1,"1",1);
  61. sqlite3_reader reader_= cmd1.executereader();
  62. while(reader_.read())
  63. {
  64. cout<<"number : "<<reader_.getint(0)<<std::endl;
  65. cout<<"string : "<<reader_.getstring(1)<<std::endl;
  66. }
  67. con.close();
  68. }
  69. catch(exception &ex) {
  70. /*
  71. 捕捉异常,输出异常信息
  72. */
  73. cerr << "Exception Occured: " << ex.what() << endl;
  74. }
  75. return 0;
  76. }

猜你在找的Sqlite相关文章