C++ 实现sqilte创建数据库插入、更新、查询、删除
C/C++ Interface APIs
Following are important C/C++ SQLite interface routines, which can suffice your requirement to work with SQLite database from your C/C++ program. If you are looking for a more sophisticated application, then you can look into SQLite official documentation.
Sr.No. | API & Description |
---|---|
1 |
sqlite3_open(const char *filename, sqlite3 **ppDb) This routine opens a connection to an SQLite database file and returns a database connection object to be used by other SQLite routines. If the filename argument is NULL or ':memory:', sqlite3_open() will create an in-memory database in RAM that lasts only for the duration of the session. If the filename is not NULL, sqlite3_open() attempts to open the database file by using its value. If no file by that name exists, sqlite3_open() will open a new database file by that name. |
2 |
sqlite3_exec(sqlite3*, const char *sql, sqlite_callback, void *data, char **errmsg) This routine provides a quick, easy way to execute SQL commands provided by sql argument which can consist of more than one SQL command. Here, the first argument sqlite3 is an open database object, sqlite_callback is a call back for which data is the 1st argument and errmsg will be returned to capture any error raised by the routine. SQLite3_exec() routine parses and executes every command given in the sql argument until it reaches the end of the string or encounters an error. |
3 |
sqlite3_close(sqlite3*) This routine closes a database connection previously opened by a call to sqlite3_open(). All prepared statements associated with the connection should be finalized prior to closing the connection. If any queries remain that have not been finalized, sqlite3_close() will return SQLITE_BUSY with the error message Unable to close due to unfinalized statements. |
Connect To Database
Following C code segment shows how to connect to an existing database. If the database does not exist, then it will be created and finally a database object will be returned.
#include <stdio.h>
#include <sqlite3.h> int main(int argc, char* argv[]) {
sqlite3 *db;
char *zErrMsg = 0;
int rc; rc = sqlite3_open("test.db", &db); if( rc ) {
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
return(0);
} else {
fprintf(stderr, "Opened database successfully\n");
}
sqlite3_close(db);
}
Now, let's compile and run the above program to create our database test.db in the current directory. You can change your path as per your requirement.
$gcc test.c -l sqlite3
$./a.out
Opened database successfully
If you are going to use C++ source code, then you can compile your code as follows −
$g++ test.c -l sqlite3
Here, we are linking our program with sqlite3 library to provide required functions to C program. This will create a database file test.db in your directory and you will have the following result.
-rwxr-xr-x. 1 root root 7383 May 8 02:06 a.out
-rw-r--r--. 1 root root 323 May 8 02:05 test.c
-rw-r--r--. 1 root root 0 May 8 02:06 test.db
Create a Table
Following C code segment will be used to create a table in the previously created database −
#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h> static int callback(void *NotUsed, int argc, char **argv, char **azColName) {
int i;
for(i = 0; i<argc; i++) {
printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
}
printf("\n");
return 0;
} int main(int argc, char* argv[]) {
sqlite3 *db;
char *zErrMsg = 0;
int rc;
char *sql; /* Open database */
rc = sqlite3_open("test.db", &db); if( rc ) {
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
return(0);
} else {
fprintf(stdout, "Opened database successfully\n");
} /* Create SQL statement */
sql = "CREATE TABLE COMPANY(" \
"ID INT PRIMARY KEY NOT NULL," \
"NAME TEXT NOT NULL," \
"AGE INT NOT NULL," \
"ADDRESS CHAR(50)," \
"SALARY REAL );"; /* Execute SQL statement */
rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg); if( rc != SQLITE_OK ){
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
} else {
fprintf(stdout, "Table created successfully\n");
}
sqlite3_close(db);
return 0;
}
When the above program is compiled and executed, it will create COMPANY table in your test.db and the final listing of the file will be as follows −
-rwxr-xr-x. 1 root root 9567 May 8 02:31 a.out
-rw-r--r--. 1 root root 1207 May 8 02:31 test.c
-rw-r--r--. 1 root root 3072 May 8 02:31 test.db
INSERT Operation
Following C code segment shows how you can create records in COMPANY table created in the above example −
#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h> static int callback(void *NotUsed, int argc, char **argv, char **azColName) {
int i;
for(i = 0; i<argc; i++) {
printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
}
printf("\n");
return 0;
} int main(int argc, char* argv[]) {
sqlite3 *db;
char *zErrMsg = 0;
int rc;
char *sql; /* Open database */
rc = sqlite3_open("test.db", &db); if( rc ) {
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
return(0);
} else {
fprintf(stderr, "Opened database successfully\n");
} /* Create SQL statement */
sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) " \
"VALUES (1, 'Paul', 32, 'California', 20000.00 ); " \
"INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) " \
"VALUES (2, 'Allen', 25, 'Texas', 15000.00 ); " \
"INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)" \
"VALUES (3, 'Teddy', 23, 'Norway', 20000.00 );" \
"INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)" \
"VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 );"; /* Execute SQL statement */
rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg); if( rc != SQLITE_OK ){
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
} else {
fprintf(stdout, "Records created successfully\n");
}
sqlite3_close(db);
return 0;
}
When the above program is compiled and executed, it will create the given records in COMPANY table and will display the following two lines −
Opened database successfully
Records created successfully
SELECT Operation
Before proceeding with actual example to fetch records, let us look at some detail about the callback function, which we are using in our examples. This callback provides a way to obtain results from SELECT statements. It has the following declaration −
typedef int (*sqlite3_callback)(
void*, /* Data provided in the 4th argument of sqlite3_exec() */
int, /* The number of columns in row */
char**, /* An array of strings representing fields in the row */
char** /* An array of strings representing column names */
);
If the above callback is provided in sqlite_exec() routine as the third argument, SQLite will call this callback function for each record processed in each SELECT statement executed within the SQL argument.
Following C code segment shows how you can fetch and display records from the COMPANY table created in the above example −
#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h> static int callback(void *data, int argc, char **argv, char **azColName){
int i;
fprintf(stderr, "%s: ", (const char*)data); for(i = 0; i<argc; i++){
printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
} printf("\n");
return 0;
} int main(int argc, char* argv[]) {
sqlite3 *db;
char *zErrMsg = 0;
int rc;
char *sql;
const char* data = "Callback function called"; /* Open database */
rc = sqlite3_open("test.db", &db); if( rc ) {
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
return(0);
} else {
fprintf(stderr, "Opened database successfully\n");
} /* Create SQL statement */
sql = "SELECT * from COMPANY"; /* Execute SQL statement */
rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg); if( rc != SQLITE_OK ) {
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
} else {
fprintf(stdout, "Operation done successfully\n");
}
sqlite3_close(db);
return 0;
}
When the above program is compiled and executed, it will produce the following result.
Opened database successfully
Callback function called: ID = 1
NAME = Paul
AGE = 32
ADDRESS = California
SALARY = 20000.0 Callback function called: ID = 2
NAME = Allen
AGE = 25
ADDRESS = Texas
SALARY = 15000.0 Callback function called: ID = 3
NAME = Teddy
AGE = 23
ADDRESS = Norway
SALARY = 20000.0 Callback function called: ID = 4
NAME = Mark
AGE = 25
ADDRESS = Rich-Mond
SALARY = 65000.0 Operation done successfully
UPDATE Operation
Following C code segment shows how we can use UPDATE statement to update any record and then fetch and display updated records from the COMPANY table.
#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h> static int callback(void *data, int argc, char **argv, char **azColName){
int i;
fprintf(stderr, "%s: ", (const char*)data); for(i = 0; i<argc; i++) {
printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
}
printf("\n");
return 0;
} int main(int argc, char* argv[]) {
sqlite3 *db;
char *zErrMsg = 0;
int rc;
char *sql;
const char* data = "Callback function called"; /* Open database */
rc = sqlite3_open("test.db", &db); if( rc ) {
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
return(0);
} else {
fprintf(stderr, "Opened database successfully\n");
} /* Create merged SQL statement */
sql = "UPDATE COMPANY set SALARY = 25000.00 where ID=1; " \
"SELECT * from COMPANY"; /* Execute SQL statement */
rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg); if( rc != SQLITE_OK ) {
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
} else {
fprintf(stdout, "Operation done successfully\n");
}
sqlite3_close(db);
return 0;
}
When the above program is compiled and executed, it will produce the following result.
Opened database successfully
Callback function called: ID = 1
NAME = Paul
AGE = 32
ADDRESS = California
SALARY = 25000.0 Callback function called: ID = 2
NAME = Allen
AGE = 25
ADDRESS = Texas
SALARY = 15000.0 Callback function called: ID = 3
NAME = Teddy
AGE = 23
ADDRESS = Norway
SALARY = 20000.0 Callback function called: ID = 4
NAME = Mark
AGE = 25
ADDRESS = Rich-Mond
SALARY = 65000.0 Operation done successfully
DELETE Operation
Following C code segment shows how you can use DELETE statement to delete any record and then fetch and display the remaining records from the COMPANY table.
#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h> static int callback(void *data, int argc, char **argv, char **azColName) {
int i;
fprintf(stderr, "%s: ", (const char*)data); for(i = 0; i<argc; i++) {
printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
}
printf("\n");
return 0;
} int main(int argc, char* argv[]) {
sqlite3 *db;
char *zErrMsg = 0;
int rc;
char *sql;
const char* data = "Callback function called"; /* Open database */
rc = sqlite3_open("test.db", &db); if( rc ) {
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
return(0);
} else {
fprintf(stderr, "Opened database successfully\n");
} /* Create merged SQL statement */
sql = "DELETE from COMPANY where ID=2; " \
"SELECT * from COMPANY"; /* Execute SQL statement */
rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg); if( rc != SQLITE_OK ) {
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
} else {
fprintf(stdout, "Operation done successfully\n");
}
sqlite3_close(db);
return 0;
}
When the above program is compiled and executed, it will produce the following result.
Opened database successfully
Callback function called: ID = 1
NAME = Paul
AGE = 32
ADDRESS = California
SALARY = 20000.0 Callback function called: ID = 3
NAME = Teddy
AGE = 23
ADDRESS = Norway
SALARY = 20000.0 Callback function called: ID = 4
NAME = Mark
AGE = 25
ADDRESS = Rich-Mond
SALARY = 65000.0 Operation done successfully http://www.yiibai.com/sqlite/export.html
自己编了一个股票监控软件,有如下功能,有兴趣的朋友可以下载;
(1) 个股监测。监测个股实时变化,可以监测个股大单交易、急速拉升和下降、主力入场和出场、股票最高点和最低点提醒。检测到最高点、最低点、主力进场点、主力退场点、急速拉升点、急速下跌点,给出语音或者声音提醒,不用再时刻看着大盘了,给你更多自由的时间;
(2) 大盘监测。监测大盘的走势,采用上证、深证、创业三大指数的综合指数作为大盘走势。并实时监测大盘的最高点和最低点、中间的转折点。
(3) 股票推荐。还能根据历史数据长期或短期走势进行分析,对股市3千多个股票进行分析对比,选出涨势良好的股票,按照增长速度从大到小排序,推荐给你涨势良好的股票;
下载地址:
1.0.3版本(修复大盘指数崩溃缺陷)下载地址:
链接:https://pan.baidu.com/s/1BJcTp-kdniM7VE9K5Kd3vg 提取码:003h
更新链接:
https://www.cnblogs.com/bclshuai/p/10621613.html
C++ 实现sqilte创建数据库插入、更新、查询、删除的更多相关文章
- Trie树的创建、插入、查询的实现
原文:http://blog.chinaunix.net/xmlrpc.php?r=blog/article&uid=28977986&id=3807947 1.什么是Trie树 Tr ...
- MongoDB数据库中更新与删除数据
MongoDB数据库中更新与删除数据 在MongoDB数据库中,可以使用Collection对象的update方法更新集合中的数据文档.使用方法如下所示: collection.update(sele ...
- pymongo创建索引、更新、删除
pymongo创建索引.更新.删除 索引创建 ## collection 为数据集合collection.create_Index({'需创建索引字段': 1})collection.ensu ...
- SQL.Cookbook 读书笔记4 插入更新和删除
第四章 插入更新和删除 4.1 插入数据 ,'PROGRA','NEW YOURK'); 4.2 从一个表向另一个表中复制 insert into dept_east(deptno,dname,loc ...
- shell脚本操作mysql数据库—创建数据库,在该数据库中创建表(插入,查询,更新,删除操作也可以做)
#!/bin/bash HOSTNAME="192.168.1.224" #数据库Server信 ...
- SQL语句创建数据库以及一些查询练习
--创建 MyCompany数据库 use master execute sp_configure 'show advanced options',1 --开启权限 reconfigure execu ...
- C#中往数据库插入/更新时候关于NUll空值的处理
本文转载:http://blog.csdn.net/chybaby/article/details/2338943 本文转载:http://www.cnblogs.com/zfanlong1314/a ...
- SQL语句创建数据库,SQL语句删除数据库,SQL语句创建表,SQL语句删除表,SQL语句添加约束,SQL语句删除约束
创建数据库: CREATE DATABASE Test --要创建的数据库名称 ON PRIMARY ( --数据库文件的具体描述 NAME='Test_data', --主数据文件的逻辑名称 FIL ...
- Elasticsearch 使用:创建、插入、查询、更新、删除
Elasticsearch 是一个开源的搜索引擎,建立在一个全文搜索引擎库 Apache Lucene™ 基础之上. Lucene 可能是目前存在的,不论开源还是私有的,拥有最先进,高性能和全功能搜索 ...
随机推荐
- Docker学习笔记之浅谈虚拟化和容器技术
0x00 概述 相信所有对 Docker 有所耳闻的朋友都知道,它是一款以容器虚拟化技术为基础的软件,因此在了解有关 Docker 的概念知识和使用方法之前,虚拟化和容器技术是我们不可或缺的基础知识. ...
- Vue小案例 之 商品管理------学习过滤器 使用过滤器处理日期的格式
代码学习过滤器 过滤器介绍:过滤模型数据,在数据显示前做预处理操作: 内置过滤器:在1.x中,Vue提供了内置过滤器,但是在2.x中已经完全废除: 解决办法: (1)使用第三方库来替代1.x中的内置过 ...
- 写给大忙人的nginx核心配置详解
由于当前很多应该都是前后端分离了,同时大量的基于http的分布式和微服务架构,使得很多时候应用和不同项目组之间的系统相互来回调用,关系复杂.如果使用传统的做法,都在应用中进行各种处理和判断,不仅维护复 ...
- Deep Learning for NLP
Deep Learning for NLP The First Paper Proposed Bi-LSTM+CRF 我认为,第一篇提出 Bi-LSTM+CRF 架构的文章是: Huang Z, Xu ...
- Introduction To Machine Learning Self-Evaluation Test
Preface Section 1 - Mathematical background Multivariate calculus take derivatives and integrals; de ...
- bzoj 1818 [CQOI 2010] 内部白点 - 扫描线 - 树状数组
题目传送门 快速的列车 慢速的列车 题目大意 一个无限大的方格图内有$n$个黑点.问有多少个位置上下左右至少有一个黑点或本来是黑点. 扫描线是显然的. 考虑一下横着的线段,取它两个端点,横坐标小的地方 ...
- Ubuntu + CUDA9 + CUDNN7 + OpenCV3.4 + contrib +CAFFE-master
安装ubuntu时赞美Rufus(建议ubuntu16.04.04),过程参考 https://www.cnblogs.com/willnote/p/6725594.html 安 装 前 一 定 要 ...
- topcoder srm 490 div1
problem1 link 首先每$n*m$一定是一个循环,所以只需要考虑时间$[0,n*m-1]$即可.这个期间一共出现了$n$个,第i个的出现时间为$m*i$,离开的时间为$\left \lcei ...
- HDU1285 确定比赛问题【拓扑排序+优先队列】
题目 有N个比赛队(1<=N<=500),编号依次为1,2,3,....,N进行比赛,比赛结束后,裁判委员会要将所有参赛队伍从前往后依次排名,但现在裁判委员会不能直接获得每个队的比赛成绩, ...
- 使用vs code搭建C开发环境
关于搭建vscode的开发环境来开发c网上已经有很多类似的贴子,但是几乎都是直接给出tasks.json和launch.json文件,并未说明这两个文件的作用以及如何配置.这里面向纯小白着重说明下(1 ...