这样直接调用 sqlite的API就方便多了.当然sqlite3.h文件得从sqlite源代码(以sqlite-source-3_5_3.zip文件提供)中搞到.
使用VC++的LIB命令有以下步骤:
(1)设置VC98中LIB.exe所在的路径:
D:/MyDoc/db/capi>set path=%path%;"D:/Program Files/Microsoft Visual Studio/VC98/Bin"
(2)生成SQLite的lib文件:
(如果只有dll,没有def文件,则在命令行执行:
dumpbin /exports sqlite3.dll > sqlite3.def
编辑 sqlite3.def 文件,使之格式与.def文件格式一致。比如:
将前面的编号去掉。)
D:/MyDoc/db/capi>lib /def:sqlite3.def /machine:i386 /out:sqlite3.lib
Microsoft (R) Library Manager Version 6.00.8168 Copyright (C) Microsoft Corp 1992-1998. All rights reserved. Creating library SQLITE.lib and object SQLITE.exp
这样就成功地创建了在WIN32程序中访问sqlite所需要的库,可以用于链接WIN32程序.
到此所有使用sqlite的准备工作已告罄.现在在MSVC6中新建一个Win32 Console Application工程,把sqlite.dll,sqlite.h和sqlite.lib文件复制到工程文件夹中,把sqlite.h文件加入到项目中,然后在Project Setting的Link中的对象库模块中增加sqlite.lib文件.
然后修改加入如下代码即可:
// 使用ISO C++来访问SQLite
#include <iostream>
#include <string>
#include <sstream>
#include "sqlite3.h"
using namespace std;
sqlite3* pDB;
int createTable()
{
char* errMsg;
std::string dropTab="drop table test_tab;";
string strSQL= "create table test_tab (f1 int, f2 long);";
int res = sqlite3_exec(pDB,dropTab.c_str(),0,0, &errMsg);
if (res != SQLITE_OK)
{
std::cout << "执行SQL 出错." << errMsg << std::endl;
return -1;
}
res = sqlite3_exec(pDB,strSQL.c_str(),0,0, &errMsg);
if (res != SQLITE_OK)
{
std::cout << "执行创建table的SQL 出错." << errMsg << std::endl;
return -1;
}
else
{
std::cout << "创建table的SQL成功执行."<< std::endl;
}
return 0;
}
int insert1()
{
char* errMsg;
int res = sqlite3_exec(pDB,"begin transaction;",0,0, &errMsg);
for (int i= 1; i < 10; ++i)
{
std::stringstream strsql;
strsql << "insert into test_tab values(";
strsql << i << ","<< (i+10) << ");";
std::string str = strsql.str();
res = sqlite3_exec(pDB,str.c_str(),0,0, &errMsg);
if (res != SQLITE_OK)
{
std::cout << "执行SQL 出错." << errMsg << std::endl;
return -1;
}
}
res = sqlite3_exec(pDB,"commit transaction;",0,0, &errMsg);
std::cout << "SQL成功执行."<< std::endl;
return 0;
}
static int callback(void *NotUsed, int argc, char **argv, char **azColName){
int i;
for(i=0; i<argc; i++){
std::cout<< azColName[i] << " = "<< (argv[i] ? argv[i] : "NULL")<< ", " ;
}
std::cout<< "/n";
return 0;
}
int select1()
{
char* errMsg;
string strSQL= "select * from test_tab;";
int res = sqlite3_exec(pDB,strSQL.c_str(),callback,0, &errMsg);
if (res != SQLITE_OK)
{
std::cout << "执行SQL 出错." << errMsg << std::endl;
return -1;
}
else
{
std::cout << "SQL成功执行."<< std::endl;
}
return 0;
}
int main(int argc, char* argv[])
{
if (argc < 2)
{
std::cout << "请输入命令行参数:sqlite数据库名." << std::endl;
return 0;
}
int res = sqlite3_open(argv[1], &pDB);
if( res ){
std::cout << "Can't open database: "<< sqlite3_errmsg(pDB);
sqlite3_close(pDB);
return -1;
}
res = createTable();
if (res != 0)
{
return 0;
}
res = insert1();
if (res != 0)
{
return 0;
}
select1();
return 0;
}