前端之家收集整理的这篇文章主要介绍了
sqlite3x 的基本用法,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
sqlite3x的基本用法:
-
- #include <string>
- #include <iostream>
- #include <stdexcept>
- #include "constant.h"
- #include <time.h>
- #include "sqlite3x/sqlite3x.hpp"
-
- using namespace std;
- using namespace sqlite3x;
-
- int main(void) {
- try {
- /*
- 打开一个数据库连接,只需创建一个sqlite3_connection对象指定要连接的数
- 据库,如果数据不存在创建这个数据库。
- */
- sqlite3_connection con("test.db");
- /*
- 执行一条sql语句,查询当前系统是否存在表名为’t_test’的表
- 直接调用sqlite3_connection的方法可以执行语句,并根据语句类型返回不同类型的值,
- 当然需要调用不同的方法,比如返回一个string型的值可以调用con.executestring()方法。
- */
- int count=con.executeint("select count(*) from sqlite_master where name='t_test';");
- if(count==0)
- {
- /*
- 创建数据表:t_test,包含两个字段。
- */
- con.executenonquery("create table t_test(number,string);");
- }
- //为了测试使用和不使用事务的时候效率的区别
- time_t begin,end;
- begin = time(NULL);
- /*
- 使用事务执行语句
- */
- sqlite3_transaction trans(con);
- {
- /*
- 创建sqlite3_command对象来执行语句,对于需要给定参数的地方,可以在语句上写“?”,在用bind()方法来给定参数的实际值。
- */
- sqlite3_command cmd(con,"insert into t_test values(?,?);");
- //cmd.bind(2,"foobar",6);
- std::string ff("foobar");
- for(int i=0; i<10; i++) {
- cmd.bind(2,ff);
- cmd.bind(1,(int)i);
- cmd.executenonquery();
- }
- }
- trans.commit();
- end = time(NULL);
-
- cout<<"time"<<end-begin<<endl;
-
-
-
- //selete
- // sqlite3_command cmd(con,"select number,string from t_test where number = ?;");
- sqlite3_command cmd1(con,"select* from t_test ;");
- // cmd.bind(1,"1",1);
- sqlite3_reader reader_= cmd1.executereader();
- while(reader_.read())
- {
- cout<<"number : "<<reader_.getint(0)<<std::endl;
- cout<<"string : "<<reader_.getstring(1)<<std::endl;
- }
-
- con.close();
- }
- catch(exception &ex) {
- /*
- 捕捉异常,输出异常信息
- */
- cerr << "Exception Occured: " << ex.what() << endl;
- }
- return 0;
- }