SQlite3轻巧,效率高,是小型软件数据库的首选。近来在网上参考了些资料,自己动手编程,有些收获,整理了下代码,记下来...
源码中包括数据库数据的插入,查询等基本操作。
源码:
#include
#include
#include
using namespace std;
extern "C"
{
#include "./sqlite3.h"
};
void sqlite3_exec_report(sqlite3* db, const char* sql, sqlite3_callback func_callback, void *para);
void select_v2(sqlite3 *db, const char*sql);
void outputItem(sqlite3_stmt* stat, int nColumn, char* out_pic_path);
string GetType(int t);
//回调函数
int select_items(void *para, int n_column, char **column_val, char **column_name);//查询
int main(int args, char*argv[])
{
int result, ret;
sqlite3* db = NULL;
char* errmsg = NULL;
char module_path[100];
//获取当前exe路径
DWORD dwPathLen = GetModuleFileNameA(NULL, module_path, 100);
char *p = module_path + dwPathLen;
while (1)
{
char c = *p;
if (c == '\\')
{
*(p+1) = '\0';
break;
}
p--;
}
//合成数据库文件路径
strcat_s(module_path, 100, "db\\mydb.db");
string db_path(module_path);
//打开(创建)数据库
result = sqlite3_open(db_path.c_str(), &db);
//----------------------------第一张表------------------------------
//--不包含blob数据,通过普通的方法插入
//-- --------------------------------------------------------------
if (result == SQLITE_OK)
{
//创建第一张表
sqlite3_exec_report(db, "create table MyTable_1(ID integer autoincrement primary key, name nvarchar(30))", NULL, NULL);
//先清除数据
sqlite3_exec_report(db, "delete from MyTable_1", NULL, NULL);
//插入数据
const char * sqls[] = {
"insert into MyTable_1(ID,name) values(0, '钱学森')",
"insert into MyTable_1(ID,name) values(1, '邓稼先')",
"insert into MyTable_1(ID,name) values(2, '钱三强')",
"insert into MyTable_1(ID,name) values(3, '李四光')",
"insert into MyTable_1(ID,name) values(4, '贺才良')"
};
for (int i = 0; i < sizeof(sqls)/sizeof(char*); i++)
{
sqlite3_exec_report(db, sqls[i], NULL, NULL);
}
//查询插入的数据 用的是回调的方法
sqlite3_exec_report(db, "select * from MyTable_1", select_items, NULL);
sqlite3_close(db);
}
else
{
//打开数据库失败
cout << sqlite3_errmsg(db) << endl;
ret = -1;
}
//-----------------------------第二张表------------------------------
//--包含blob数据,通过sqlite3_prepare,sqlite3_bind_blob,sqlite3_step
//-- 的方法实现数据的插入
//-- --------------------------------------------------------------
result = sqlite3_open(module_path, &db);
if (result==SQLITE_OK)
{
sqlite3_exec_report(db, "create table stu_msg(ID integer primary key autoincrement, name nvarchar(32), picture blob)", NULL, NULL);
sqlite3_exec_report(db, "delete from stu_msg", NULL, NULL);
sqlite3_stmt *stat;
const char *pzTail = NULL;
const char *sqls[] = {
"insert into stu_msg(ID, name, picture) values(0, '华罗庚', ?);",
"insert into stu_msg(ID, name, picture) values(1, '钱学森', ?);"
};
const char *names[] = {
"pic\\hualuogen.jpg",
"pic\\qianxuesen.jpg"
};
for (int j=0; j
另外推荐一款查看sqlites数据库的软件:sqlite expert 私人版,功能很强大伊~
>_<