使用VC与GCC操作SQLite数据库的最简单Demo

来源:互联网 发布:windows线程之间通讯 编辑:程序博客网 时间:2024/06/06 02:52

一、准备工作

  到http://www.sqlite.org/download.html下载Source Code里的amalgamation版,里头有4个文件,sqlite3.c、sqlite3.h、shell.c、sqlite3ext.h。它们具体是干嘛的我还不清楚,容后具体看看,现在只是根据网上看到的方法,简单做一个Demo试试。这里我们用到的文件有sqlite3.c和sqlite3.h,sqlite3.h里声明的有各种接口函数,而sqlite3.c用于生成需要链接的库文件。这篇日志主要是记录怎么组织的文件,做个笔记。

 

二、VC6.0版

  新建一个Win32 Console Application,将自写的main.cpp及前面提到的sqlite3.h、sqlite3.c添加到工程中,直接编译运行即可。

 

三、GCC版

  将main.cpp、sqlite3.h、sqlite3.c置于同一目录下,并在同一目录下新建一文本文件makefile,执行make命令即可。

 

四、相关源码

  (1)不规范的makefile

main.exe: main.cpp sqlite3.libg++ main.cpp sqlite3.lib -o main.exesqlite3.lib: sqlite3.oar crv sqlite3.lib sqlite3.osqlite3.o:sqlite3.cgcc -c sqlite3.c -o sqlite3.o


  (2)main.cpp(源于网络http://dearymz.blog.163.com/blog/static/20565742011518102612855/)

#include "sqlite3.h"#include <stdio.h>#include <tchar.h>#include <process.h>#include <iostream>using std::cout;using std::endl;bool test(sqlite3* db){    sqlite3_stmt* stmt = NULL;     if(sqlite3_prepare_v2(db,                 "create table if not exists files("                "id int primary key not null, "                "name string unique not null, "                "size int not null, "                "data blob not null)",                 512, &stmt, NULL) != SQLITE_OK)        return false;    if(sqlite3_step(stmt) != SQLITE_DONE)        return false;    if(sqlite3_finalize(stmt) != SQLITE_OK)        return false;    if(sqlite3_prepare_v2(db,                "insert into files values(last_insert_rowid() + 1, ?, 0, ?)",                512, &stmt, NULL) != SQLITE_OK)        return false;    if(sqlite3_reset(stmt) != SQLITE_OK)        return false;    if(sqlite3_bind_text(stmt, 1, "http://dearymz.blog.163.com", -1, NULL) != SQLITE_OK)        return false;    if(sqlite3_bind_text(stmt, 2, "http://dearymz.blog.163.com", -1, NULL) != SQLITE_OK)        return false;    if(sqlite3_step(stmt) != SQLITE_DONE)        return false;    if(sqlite3_finalize(stmt) != SQLITE_OK)        return false;    if(sqlite3_prepare_v2(db,                "select count(*) from files",                512, &stmt, NULL) != SQLITE_OK)        return false;    if(sqlite3_step(stmt) != SQLITE_ROW)        return false;    cout << sqlite3_column_int(stmt, 0) << endl;    if(sqlite3_finalize(stmt) != SQLITE_OK)        return false;    return true;}int _tmain(int argc, _TCHAR* argv[]){    sqlite3* db = NULL;    if(sqlite3_open("test.db3", &db) == 0)    {        if(test(db))            cout << "OK" << endl;        else            cout << "Error!" << endl;    }    cout << sqlite3_errmsg(db) << endl;    sqlite3_close(db);    system("pause");    return 0;}