首先,把编译SQLITE生成的DLL、LIB和sqlite3.h 放到项目的文件夹下,把项目=》属性=》链接器=》输入=》附加依赖项:输入SQLITE的lib文件名
- 一、创建MySQLite.cpp:
- #include "stdafx.h"
- #include "MySQLite.h"
- bool MySQLite::sqlite_connect(char *filename)
- {
- db=NULL;
- zErrMsg = 0;
- row = 0, column = 0;
- int rc;
- rc = sqlite3_open(filename, &db); //打开指定的数据库文件,如果不存在将创建一个同名的数据库文件
- if( rc )
- {
- strcpy(zErrMsg,sqlite3_errmsg(db));//保存错误信息
- sqlite3_close(db);
- return false;
- }
- return true;
- }
- bool MySQLite::sqlite_exec(char *sql)
- {
- int rc;
- rc=sqlite3_exec( db , sql , 0 , 0 , &zErrMsg );
- if(rc == SQLITE_OK)
- return true;
- return false;
- }
- void MySQLite::sqlite_search(char *search_sql)
- {
- sqlite3_get_table( db,search_sql,&azResult,&row,&column,&zErrMsg);
- }
- bool MySQLite::sqlite_disconnect()
- {
- //释放掉 azResult 的内存空间
- sqlite3_free_table( azResult );
- if(sqlite3_close(db)==SQLITE_OK) //关闭数据库
- return true;
- return false;
- }
- 二、创建MySQLite.h:
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include "sqlite3.h"
- class MySQLite
- {
- private:
- sqlite3 *db;//数据库句柄
- char **azResult; //二维数组存放结果
- char *zErrMsg;//保存错误信息
- int row;
- int column;
- public:
- bool sqlite_connect(char *filename);//连接数据库
- bool sqlite_exec(char *sql);//执行SQL命令
- void sqlite_search(char *search_sql);//查询
- bool sqlite_disconnect();//断开数据库连接
- int GetTableRow(){return row;}//查询后,取得表“列”数
- int GetTableColumn(){return column;}//查询后,取得表“栏”数
- char *GetErrorMsg(){return zErrMsg;}//取得当前错误提示
- char *GetTableData(int x,int y){return *(azResult+x+y*column);}//查询后,取得表内某个单元值
- };
- 三、创建测试文件test.cpp:
- #include "stdafx.h"
- #include <iostream>
- #include "MySQLite.h"
- #define _DEBUG_
- using namespace std;
- int main( void )
- {
- bool result;
- MySQLite *sqlite=new MySQLite();
- result=sqlite->sqlite_connect("hellogv.db");
- if(!result) cout<<sqlite->GetErrorMsg()<<endl;
- result=sqlite->sqlite_exec("CREATE TABLE SensorData(ID INTEGER PRIMARY KEY,SensorID INTEGER,SiteNum INTEGER,Time VARCHAR(500),SensorParameterREAL);");
- if(!result) cout<<sqlite->GetErrorMsg()<<endl;
- result=sqlite->sqlite_exec("INSERT INTO \"SensorData\" VALUES(NULL , 1 , 1 , '200605011206', 18.9 );");
- if(!result) cout<<sqlite->GetErrorMsg()<<endl;
- result=sqlite->sqlite_exec("INSERT INTO \"SensorData\" VALUES(NULL , 23 , 45 , '200605011306', 16.4 );");
- if(!result) cout<<sqlite->GetErrorMsg()<<endl;
- sqlite->sqlite_search("SELECT * from SensorData");
- cout<<sqlite->GetTableColumn()<<" "<<sqlite->GetTableRow()<<endl;
- cout<<sqlite->GetTableData(0,0)<<endl;
- sqlite->sqlite_disconnect();
- return 0;
- }