240115_SQLite

Haoliang Tang Lv3

https://www.sqlite.org/index.html

SQLite是个small, fast, high-reliability数据库引擎。也许是most used的数据库,在浏览器,OS,移动端,嵌入式系统。

和其他如mysql等不同的是,SQLite不是Client/Server架构的。

Linux一般都自带SQLite了

SQLite数据库都存储在一个文件里,一般扩展名为.sqlite3,.db

SQLite轻量快速简单,适合小型项目。缺点是不支持高并发?

命令行交互

https://www.sqlite.org/quickstart.html

https://www.sqlite.org/cli.html

https://www.sqlite.org/lang_createtable.html

终端敲入sqlite3 xxx.sqlite3,进入sqlite的command-line shell,并打开xxx.sqlite3(不存在则创建)。

只敲sqlite3的话,即 If no database file is specified on the command-line, a temporary database is created and automatically deleted when the “sqlite3” program exits.虽然可以”.open” command打开,但不建议这样

虽然SQL语句是通用的,但不同dbms的shell交互命令都不尽相同,sqlite就和mysql不一样。

查看各种sqlite命令:

1
sqlite> .help

shows a list of all databases open in the current connection

1
sqlite> .databases

查看tables

1
sqlite> .tables

“.schema” command shows the complete schema for the database, or for a single table if an optional tablename argument is provided,实际就是查询建表语句:

1
2
sqlite> .schema
sqlite> .schema tbl

BACKUP备份

1
sqlite> .backup './copy.bak'

退出

1
.exit

如果是SQL语句的话注意最后要有;

让gpt自动生成插入数据,注意插入字符串值一定是单引号'',双引号出错

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
CREATE TABLE Persons (
PersonID INTEGER NOT NULL,
LastName TEXT NOT NULL,
FirstName TEXT NOT NULL,
Address TEXT,
City TEXT,
PRIMARY KEY (PersonID)
);

INSERT INTO Persons (PersonID, LastName, FirstName, Address, City)
VALUES
(56, 'Smith', 'John', '123 Main St', 'City1'),
(788, 'Doe', 'Jane', '456 Oak St', 'City2'),
(123, 'Johnson', 'Robert', '789 Maple St', 'City3'),
(999, 'Williams', 'Emily', '101 Pine St', 'City4'),
(444, 'Brown', 'Michael', '202 Cedar St', 'City5');

但命令行操作db,太しんどい。还是用可视化工具吧,Antares挺不错的。

可视化工具

  • sqlitebrowser
  • Antares
  • DbGate
  • DBeaver
1
2
3
4
sudo pacman -S sqlitebrowser
yay -S antares-sql-bin
paru -S dbgate-bin
sudo pacman -S dbeaver

Python操作SQLite

https://docs.python.org/3/library/sqlite3.html

https://www.youtube.com/watch?v=byHcYRpMgI4

使用python的sqlite3模块,已经内置,直接import就行,无需pip install。而mysql的 mysql-connector-python则需要pip install.

1
2
3
4
5
6
import sqlite3
conn = sqlite3.connect("xxx.sqlite3")
cur = conn.cursor()
cur.execute("SQL语句")
conn.commit()
conn.close()
  • Title: 240115_SQLite
  • Author: Haoliang Tang
  • Created at : 2024-01-15 00:00:00
  • Updated at : 2025-04-29 23:29:59
  • Link: https://hl-tang.github.io/2024/01/15/240115_SQLite/
  • License: This work is licensed under CC BY-NC-SA 4.0.
Comments