from:http://www.cnblogs.com/pmars/archive/2012/10/15/2724773.html
View Code
//[cpp] view plaincopyprint?
//#pragma comment(lib,"sqlite3.lib")
#include <iostream>
#include <string>
#include <sstream>
#include "sqlite3.h"
using namespace std;
sqlite3* pDB;
static int callback(void *NotUsed, int argc, char **argv, char **azColName)
{
int i =0;
std::cout<< azColName[i] << " = "<< (argv[i] ? argv[i] : "NULL")<< ", " ;
std::cout<< "\n";
return 0;
}
int main()
{
int res = sqlite3_open("mydatabase.db", &pDB);
if( res ){
std::cout << "Can't open database: "<< sqlite3_errmsg(pDB);
sqlite3_close(pDB);
return -1;
}
char* errMsg;
string dropTab="drop table test;";
string createStrSQL= "create table test(one int, two long);";
int res;
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,createStrSQL.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;
for (int i= 1; i < 10; ++i)
{
stringstream strsql;
strsql << "insert into test 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;
}
}
string strSQL= "select * from test;";
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;
}