加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

sqlite3x 的基本用法

发布时间:2020-12-12 20:10:52 所属栏目:百科 来源:网络整理
导读: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 {/*打开一个数据库连接,只需创建一个

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;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读