Linux c++ 试验-3 Sqlite3使用

2021/10/2 19:10:59

本文主要是介绍Linux c++ 试验-3 Sqlite3使用,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1、代码如下

#include <iostream>
#include <string>
#include "sqlite3.h"
using namespace std;
//输出数据
static int callback(void *data, int args_num, char **argv, char **argc)
{
	cout << *(int*)data << endl;//输出传入的值
	for (int i = 0; i < args_num; i++)
	{
		cout << argc[i] << " = " << (argv[i] ? argv[i] : "NULL") << "\t";
	}
	cout << endl;
	return 0;
}
int main()
{
	sqlite3 *db;
	char *errMsg;

	//定义
	//创建表
	string createDbsql = "create table user(ID integer PRIMARY KEY autoincrement,age INT NOT NULL,mobile INT NOT NULL,name TEXT NOT NULL)";
	//插入数据
	string insertsql = "insert into user (name,age,mobile) values ('xxx',12,'13xxxxxxxxxxxx')";
	//删除数据
	string deletesql = "delete from user where id=1";
	//检索数据
	string selectsql = "select * from user";
	//打开创建数据库
	int rc = sqlite3_open("/data/testsqlite3.db", &db);
	if (rc != SQLITE_OK)
	{
		cout << "open sqlite3 fail." << endl;
		return -1;
	}
	cout << "open sqlite3 ok." << endl;

	int rs = sqlite3_exec(db, createDbsql.c_str(), 0, 0, &errMsg);
	if (rs != SQLITE_OK)
	{
		cout << "create table fail" << endl;
	}
	else
	{
		cout << "create table ok." << endl;
	}

	//插入数据
	rs = sqlite3_exec(db, insertsql.c_str(), 0, 0, &errMsg);
	if (rs != SQLITE_OK)
	{
		cout << "insert fail" << endl;
	}
	else
	{
		cout << "insert data ok." << endl;
	}

	//检索数据:callback方式
	cout << "callback................." << endl;
	int first = 111;//传入callback数据
	sqlite3_exec(db, selectsql.c_str(), callback, (void *)&first, &errMsg);

	cout << "gettable................." << endl;
	cout << "first=" << first << endl;

	// //删除数据
	// rs = sqlite3_exec(db, deletesql.c_str(), 0, 0, &errMsg);
	// if (rs != SQLITE_OK)
	// {
	// 	cout << "delete fail" << endl;
	// }
	// else
	// {
	// 	cout << "delete data ok." << endl;
	// }

	//检索数据:gettable方式
	char **pResult;
	int nRow;
	int nCol;
	int nResult = sqlite3_get_table(db, selectsql.c_str(), &pResult, &nRow, &nCol, &errMsg);
	if (nResult != SQLITE_OK)
	{
		sqlite3_close(db);
		cout << errMsg << endl;
		sqlite3_free(errMsg);
		return 0;
	}
	string strOut;
	int nIndex = nCol;
	for (int i = 0; i < nRow; i++)
	{
		for (int j = 0; j < nCol; j++)
		{
			strOut += pResult[j];
			strOut += ":";
			strOut += pResult[nIndex];
			strOut += "\n";
			++nIndex;
		}
	}
	cout << strOut << endl;
	sqlite3_close(db);
	return 0;
}

2、安装libsqlite3

sudo apt-get install libsqlite3

3、编译

g++  -o main testsqlite3.cpp  -L /usr/local/lib -I/usr/local/include -lsqlite3

4、运行
image



这篇关于Linux c++ 试验-3 Sqlite3使用的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程