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

送分小仙女□ 提交于 2020-08-19 02:55:43

    在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函数就是做字符转换用的。

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!