SQLITE3数据库安装及使用

数据库系统一般分为大型、中型、小型。其中大型常见的有 Oracle 、DB2 等,中型有 ms-sqlserver、MySQL 等,小型的有 access 、Sqlite3 等。本文就是给大家介绍其中的小型数据库 sqlite3 。

SQLITE3 之所以被称为嵌入式数据库,就是因为其开源(总代码行约 3 万行 C 语言代码)、轻量级(体积小、容量大2T)、可移植易于集成等特点,特别适用于嵌入式平台。

Sqlite3安装

在线安装

在 Ubuntu 平台,直接使用 apt-get 命令进行安装

sudo apt-get install sqlite3

源码编译安装

下载源码

源码下载地址:https://www.sqlite.org/download.html
在这里插入图片描述
此处以 sqlite-autoconf-3460000.tar.gz 为例进行下载。

编译安装

上传下载的源码包到目标服务器,直接解压,进入解压目录后,编译安装即可(全部使用默认选项)

tar -zxf sqlite-autoconf-3460000.tar.gz
cd sqlite-autoconf-3460000/
./configure
make
sudo make install

安装测试

直接通过命令查看版本号即可验证:

[sheep@ubuntu2204:~/tools/sqlite-autoconf-3460000]$ sqlite3 --version
3.46.0 2024-05-23 13:25:27 96c92aba00c8375bc32fafcdf12429c58bd8aabfcadab6683e35bbb9cdebf19e (64-bit)

Sqlite3 的简单使用

创建数据库

创建数据库的命令为 sqlite3 xxx.db ,如创建并打开 test 数据库:sqlite3 test.db

[sheep@ubuntu2204:~/tools/sqlite-autoconf-3460000]$ sqlite3  test.db
SQLite version 3.46.0 2024-05-23 13:25:27
Enter ".help" for usage hints.
sqlite>

执行后会自动进入数据库管理界面,其中的 sqlite> 就是数据库终端提示符。

.help 会显示当前数据库所有的默认命令:

sqlite> .help
.archive ...             Manage SQL archives
.auth ON|OFF             Show authorizer callbacks
.backup ?DB? FILE        Backup DB (default "main") to FILE
.bail on|off             Stop after hitting an error.  Default OFF
.cd DIRECTORY            Change the working directory to DIRECTORY
.changes on|off          Show number of rows changed by SQL
.check GLOB              Fail if output since .testcase does not match
.clone NEWDB             Clone data into NEWDB from the existing database
.connection [close] [#]  Open or close an auxiliary database connection
.databases               List names and files of attached databases
.dbconfig ?op? ?val?     List or change sqlite3_db_config() options
.dbinfo ?DB?             Show status information about the database
.dump ?OBJECTS?          Render database content as SQL
.echo on|off             Turn command echo on or off
.eqp on|off|full|...     Enable or disable automatic EXPLAIN QUERY PLAN
.excel                   Display the output of next command in spreadsheet
.exit ?CODE?             Exit this program with return-code CODE
.expert                  EXPERIMENTAL. Suggest indexes for queries
.explain ?on|off|auto?   Change the EXPLAIN formatting mode.  Default: auto
.filectrl CMD ...        Run various sqlite3_file_control() operations
.fullschema ?--indent?   Show schema and the content of sqlite_stat tables
.headers on|off          Turn display of headers on or off
.help ?-all? ?PATTERN?   Show help text for PATTERN
.import FILE TABLE       Import data from FILE into TABLE
.indexes ?TABLE?         Show names of indexes
.intck ?STEPS_PER_UNLOCK?  Run an incremental integrity check on the db
.limit ?LIMIT? ?VAL?     Display or change the value of an SQLITE_LIMIT
.lint OPTIONS            Report potential schema issues.
.load FILE ?ENTRY?       Load an extension library
.log FILE|on|off         Turn logging on or off.  FILE can be stderr/stdout
.mode MODE ?OPTIONS?     Set output mode
.nonce STRING            Suspend safe mode for one command if nonce matches
.nullvalue STRING        Use STRING in place of NULL values
.once ?OPTIONS? ?FILE?   Output for the next SQL command only to FILE
.open ?OPTIONS? ?FILE?   Close existing database and reopen FILE
.output ?FILE?           Send output to FILE or stdout if FILE is omitted
.parameter CMD ...       Manage SQL parameter bindings
.print STRING...         Print literal STRING
.progress N              Invoke progress handler after every N opcodes
.prompt MAIN CONTINUE    Replace the standard prompts
.quit                    Stop interpreting input stream, exit if primary.
.read FILE               Read input from FILE or command output
.recover                 Recover as much data as possible from corrupt db.
.restore ?DB? FILE       Restore content of DB (default "main") from FILE
.save ?OPTIONS? FILE     Write database to FILE (an alias for .backup ...)
.scanstats on|off|est    Turn sqlite3_stmt_scanstatus() metrics on or off
.schema ?PATTERN?        Show the CREATE statements matching PATTERN
.separator COL ?ROW?     Change the column and row separators
.sha3sum ...             Compute a SHA3 hash of database content
.shell CMD ARGS...       Run CMD ARGS... in a system shell
.show                    Show the current values for various settings
.stats ?ARG?             Show stats or turn stats on or off
.system CMD ARGS...      Run CMD ARGS... in a system shell
.tables ?TABLE?          List names of tables matching LIKE pattern TABLE
.timeout MS              Try opening locked tables for MS milliseconds
.timer on|off            Turn SQL timer on or off
.trace ?OPTIONS?         Output each SQL statement as it is run
.version                 Show source, library and compiler versions
.vfsinfo ?AUX?           Information about the top-level VFS
.vfslist                 List all available VFSes
.vfsname ?AUX?           Print the name of the VFS stack
.width NUM1 NUM2 ...     Set minimum column widths for columnar output
sqlite>

.q 表示退出

sqlite> .q

如果出现 ...> 表示命令尚未输入完毕,用 ; 结束命令。如下:

sqlite> alter table user add age int
   ...> ;

创建数据库表

使用 SQL 语句(结构化查询语言,关系型数据库的通用操作语言)创建测试表,语法为 create table 表名(列名 类型, 列名 类型,....); 如:

sqlite> create table user(id int,name text, pass text);

注意:SQL 语句必须以 ; 结尾表示语句结束;Sqlite3 中所有以.开头的命令都是内置系统命令,否则按照 SQL 语句执行。

数据类型常用的有: int 整形、 real 浮点数、text 文本、 blob 二进制

比如在 user 表里加个 age 字段,类型为 int :

sqlite> alter table user add age int;

.schema user 命令是列出表结构的系统内置命令:

sqlite> .schema user
CREATE TABLE user(id int,name text, pass text, age int);
sqlite>

表的增删改查

表的增加

即 insert 操作,语法为 insert into 表名(列名,列名,...) values (值1,值2,...);,eg:

sqlite> insert into user(id,name,pass) values (1,'zhangsan','123456');
sqlite> insert into user values(2,'abc','123456',23);
sqlite> insert into user(id) values (3);
sqlite>

创建带有主键,id 自动增长的测试表:

sqlite> create table login (id INTEGER PRIMARY KEY AUTOINCREMENT,name text);

表的删除(delete)修改(update) 对应 SQL 命令各位同学可以自行探索,此处就不再举例说明了。

    删除的语法为:delete from 表名称 [条件];

    修改的语法为:update 表名称 set 列名 = 值 [条件];

表的查询

查询的语法为:select 列名 from 表名称 [条件]; eg:

sqlite> select * from user;
1|zhangsan|123456|
2|abc|123456|23
3|||
sqlite> select id from user;
1
2
3
sqlite> select id,pass from user;
1|123456
2|123456
3|
sqlite> select * from user where id = 1;
1|zhangsan|123456|
sqlite> select * from user where  id > 2;
3|||
sqlite> select * from user where  id > 1 and name = 'abc';
2|abc|123456|23
sqlite> select * from user where  id < 10 or id > 20;
1|zhangsan|123456|
2|abc|123456|23
3|||
sqlite>

数据库的表批量处理

数据库的脚本导出语法是 sqlite3 xxx.db .dump > xxx.sql , 如导出 test.db 的表 :

[sheep@ubuntu2204:~/tools/sqlite-autoconf-3460000]$ sqlite3  test.db  .dump > test.sql
[sheep@ubuntu2204:~/tools/sqlite-autoconf-3460000]$ cat test.sql
PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;
CREATE TABLE user(id int,name text, pass text, age int);
INSERT INTO user VALUES(1,'zhangsan','123456',NULL);
INSERT INTO user VALUES(2,'abc','123456',23);
INSERT INTO user VALUES(3,NULL,NULL,NULL);
CREATE TABLE login (id INTEGER PRIMARY KEY AUTOINCREMENT,name text);
DELETE FROM sqlite_sequence;
COMMIT;
[sheep@ubuntu2204:~/tools/sqlite-autoconf-3460000]$

数据库的脚本导入语法为 sqlite3 xxx.db < xxx.sql ,此处不再举例说明。

Sqlite3 的编程接口

Sqlite3 是一个三方库形式引入系统,所以必须有如下两个规则:

  1. 编写代码必须包含其默认的库头文件: #include <sqlite3.h>
  2. 编译代码必须加载其默认的库支持: gcc xxx.c -l sqlite3

Sqlite3对外提供的接口框架如下:

  1. 打开数据库表:sqlite3_open()
  2. 操作表:sqlite3_get_table()sqlite3_exec()
  3. 关闭数据库:sqlite3_close()

打开数据库

int sqlite3_open(
					const char *filename,   /* Database filename (UTF-8) */
					sqlite3 **ppDb          /* OUT: SQLite db handle */
				);

功能:该函数可以用于打开 指定路径+名称 的 sqlite3 数据库;

参数:filename 要打开的数据库路径+名称;ppdb 打开之后的数据库句柄;

返回值:成功 0;失败 -1;

关闭数据库

int sqlite3_close(sqlite3 *db);

功能:关闭已经打开的数据库;

参数:db 要关闭的数据库句柄

返回值: 成功 0;失败-1;

数据库操作 – 查询

int sqlite3_get_table(
						sqlite3 *db,          /* An open database */
						const char *zSql,     /* SQL to be evaluated */
						char ***pazResult,    /* Results of the query */
						int *pnRow,           /* Number of result rows written here */
						int *pnColumn,        /* Number of result columns written here */
						char **pzErrmsg       /* Error msg written here */
						);

功能:该函数主要用于对数据库中指定表的查询操作;

参数:
     db 已经打开的数据库句柄 == sqlite3_open的参数2 的值;
     zSql 表示要在数据库中执行的sql语句,一般是select语句;
     pazResult 结果集,表示最终查询的结果地址;
     pnRow 结果集中数据的行个数;
     pnColum 结果集中数据的列个数;
     pzErrmsg 查询异常的信息记录;

返回值:成功 0;失败 -1;

数据库操作 – 通用

int sqlite3_exec(
			sqlite3*db,                                  /* An open database */
			const char *sql,                           /* SQL to be evaluated */
			int (*callback)(void*arg,int,char**,char**),  /* Callback function */
			void * arg,                                  /* 1st argument to callback */
			char **errmsg                              /* Error msg written here */
			);

功能:该函数用于数据库中所有的常规操作,主要用于可能改动数据的增加、删除、修改操作。

参数:
     db 要执行操作的数据库句柄;
     sql 要执行的sql操作语句,主要是 insert delete update
     callback 回调函数指针,只用于查询的时候生效。
     arg 回调函数的第一个参数;
     errmsg 执行sql的异常信息;

返回值:成功 0;失败 -1

其中的参数 callback 回调函数说明:

int (*callback)( void*arg,int num ,char** va,char**na),  /* Callback function */

功能:callback 用于 sqlite3_exec 执行查询语句的是调用;

参数:
     arg 由外部sqtlie3_exec的传入的参数;
     num 执行sql语句的结果个数;
     va 执行sql之后的数据值
     na 执行sql之后的数据列名称

返回值: 成功 0; 失败 -1;

注意:该回调函数在每查询到一条记录就执行一次;

  • 39
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

aSimpleSheep

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值