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-12-18git仓库有更新,jenkins 自动触发拉代码怎么配置的?-icode9专业技术文章分享
- 2024-12-18Jenkins webhook 方式怎么配置指定的分支?-icode9专业技术文章分享
- 2024-12-13Linux C++项目实战入门教程
- 2024-12-13Linux C++编程项目实战入门教程
- 2024-12-11Linux部署Scrapy教程:新手入门指南
- 2024-12-11怎么将在本地创建的 Maven 仓库迁移到 Linux 服务器上?-icode9专业技术文章分享
- 2024-12-10Linux常用命令
- 2024-12-06谁看谁服! Linux 创始人对于进程和线程的理解是…
- 2024-12-04操作系统教程:新手入门及初级技巧详解
- 2024-12-04操作系统入门:新手必学指南