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、运行
这篇关于Linux c++ 试验-3 Sqlite3使用的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-12如何创建可引导的 ESXi USB 安装介质 (macOS, Linux, Windows)
- 2024-11-08linux的 vi编辑器中搜索关键字有哪些常用的命令和技巧?-icode9专业技术文章分享
- 2024-11-08在 Linux 的 vi 或 vim 编辑器中什么命令可以直接跳到文件的结尾?-icode9专业技术文章分享
- 2024-10-22原生鸿蒙操作系统HarmonyOS NEXT(HarmonyOS 5)正式发布
- 2024-10-18操作系统入门教程:新手必看的基本操作指南
- 2024-10-18初学者必看:操作系统入门全攻略
- 2024-10-17操作系统入门教程:轻松掌握操作系统基础知识
- 2024-09-11Linux部署Scrapy学习:入门级指南
- 2024-09-11Linux部署Scrapy:入门级指南
- 2024-08-21【Linux】分区向左扩容的方法