C++ sqlite基本操作代碼示例

    在sqlitebrowser中創建一個數據庫,添加一些數據。如下:

     用vs2017創建C++控制檯項目,配置好sqlite sdk,.h, .lib, .dll, 即可進項編程了。C++代碼:

/*

sqlite數據庫基本使用

*/

#include <iostream>
#include "sqlite3.h"
#include <Windows.h>

#pragma comment(lib, "sqlite3.lib")

using namespace std;

sqlite3 * pDB = NULL;

//UTF8 to GB2312  
char* U2G(const char* utf8)
{
	int len = MultiByteToWideChar(CP_UTF8, 0, utf8, -1, NULL, 0);

	wchar_t* wstr = new wchar_t[len + 1];
	memset(wstr, 0, len + 1);

	MultiByteToWideChar(CP_UTF8, 0, utf8, -1, wstr, len);
	len = WideCharToMultiByte(CP_ACP, 0, wstr, -1, NULL, 0, NULL, NULL);

	char* str = new char[len + 1];
	memset(str, 0, len + 1);

	WideCharToMultiByte(CP_ACP, 0, wstr, -1, str, len, NULL, NULL);

	if (wstr)
	{
		delete[] wstr;
		wstr = NULL;
	}

	return str;
}

void closeDB()
{
	sqlite3_close(pDB);
	pDB = nullptr;
}

bool SelectALL(const char* sql)
{
	sqlite3_stmt *stmt = NULL;   //stmt語句句柄

	//進行查詢前的準備工作——檢查語句合法性
	//-1代表系統會自動計算SQL語句的長度
	int result = sqlite3_prepare_v2(pDB, sql, -1, &stmt, NULL);

	if (result == SQLITE_OK) 
	{
		cout << "查詢語句OK" << endl;
		cout << "id\t" << "name\t" << "math\t" << "english\t" << "yuwen\t" << endl;

		// 每調一次sqlite3_step()函數,stmt語句句柄就會指向下一條記錄
		while (sqlite3_step(stmt) == SQLITE_ROW) 
		{
			// 取出第各列字段的值
			const unsigned char *id = sqlite3_column_text(stmt, 0);
			const unsigned char *name = sqlite3_column_text(stmt, 1);
			int math = sqlite3_column_int(stmt, 2);
			int english = sqlite3_column_int(stmt, 3);
			int yuwen = sqlite3_column_int(stmt, 4);

			//輸出相關查詢的數據
			cout << id << "\t" << U2G((const char*)name) << "\t" << math << "\t" << english << "\t" << yuwen << endl;
		}
	}
	else 
	{
		std::clog << "查詢語句有問題";
	}

	//清理語句句柄,準備執行下一個語句
	sqlite3_finalize(stmt);

	return true;
}

int main()
{
	//連接sqlite3
	int nRes = sqlite3_open("D:\\TestFiles\\student.db", &pDB);
	if (nRes != SQLITE_OK)
	{
		cout << "open db failed: " << sqlite3_errmsg(pDB);
		closeDB();
		return -1;
	}
	else
	{
		cout << "open db suceess" << endl;
	}

	//查詢數據
	const char* sql1 = "select * from score;";
	SelectALL(sql1);

	return 0;
}

      運行結果:

       查詢到的中文會有亂碼,需要做轉換,sqlite的說明:

       Note to Windows users: The encoding used for the filename argument of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever codepage is currently defined。

        代碼中U2G函數就是做字符轉換用的。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章