sqlite命令行使用方法

最近为了省钱,就打算使用开源免费的sqlite来做数据库。并且由于个人习惯,所以偏爱命令行。这里就来记录一下如何使用命令行来使用sqlite。

安装的话,macOS自带sqlite3,Linux可以使用软件包( apt-get或者 yum下载)。

这里介绍一下数据库之外的一些小操作。

以macOS为例,打开”终端”之后,输入以下命令来打开一个数据库(没有的话会新建一个):

sqlite3 名称.db

这时候就会进入sqlite操作界面,如下:

$ sqlite3 test.sql
SQLite version 3.36.0 2021-06-18 18:58:49
Enter ".help" for usage hints.

sqlite>

使用.help来查看 点操作,例如保存成新文件,修改显示模式等,如下(有空了我会翻译一下这部分内容的):

sqlite> .help
.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
.binary on|off           Turn binary output on or off.  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
.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
.imposter INDEX TABLE    Create imposter table TABLE on index INDEX
.indexes ?TABLE?         Show names of indexes
.limit ?LIMIT? ?VAL?     Display or change the value of an SQLITE_LIMIT
.lint OPTIONS            Report potential schema issues.

.log FILE|off            Turn logging on or off.  FILE can be stderr/stdout
.mode MODE ?TABLE?       Set output mode
.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                    Exit this program
.read FILE               Read input from FILE
.recover                 Recover as much data as possible from corrupt db.

.restore ?DB? FILE       Restore content of DB (default "main") from FILE
.save FILE               Write in-memory database into FILE
.scanstats on|off        Turn sqlite3_stmt_scanstatus() metrics on or off
.schema ?PATTERN?        Show the CREATE statements matching PATTERN
.selftest ?OPTIONS?      Run tests defined in the SELFTEST table
.separator COL ?ROW?     Change the column and row separators
.session ?NAME? CMD ...  Create or control sessions
.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
.testcase NAME           Begin redirecting output to 'testcase-out.txt'
.testctrl CMD ...        Run various sqlite3_test_control() operations
.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
.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可以输入 .exit,或者按下 Control + D来退出,情形如下:

sqlite> .exit

需要注意的是:除了点操作之外,其他命令都要以分号结尾(;),不然sqlite会认为命令没有结束,而出现以下情况:

sqlite> CREATE TABLE tbl2 (
   ...>

这种情况我们可以输入分号来表示命令的结束,也可以利用这一点来输入长命令,例如下面这样:

sqlite> CREATE TABLE tbl2 (
   ...>   f1 varchar(30) primary key,
   ...>   f2 text,
   ...>   f3 real
   ...> );
sqlite>

在学会一些基础操作之后,马上就要开始了解数据库四大技能:增删改查。
不过我们得新建一个表格。这里我们新建一个2列的表格,第一列名为” one“,数据类型是 varchar(一种字符类型),最大字符数量为20;第二列名为” two“,是 smallint(一种整数类型),输入命令如下:

sqlite> create table tbl1(one varchar(10), two smallint);

“在这里就是插入(insert)一条数据,方式如下:

sqlite> insert into tbl1 values('hello!',10);
sqlite> insert into tbl1 values('goodbye', 20);

这里我们插入了两行数据。然后我们来查看一下(这里展示了默认情况和修改模式之后的样式):

sqlite> select * from tbl1;
hello!|10
goodbye|20
sqlite> .mode column
sqlite> select * from tbl1;
one      two
goodbye  20

然后我们插入几条数据变成下面这样来演示删除多条数据:

one      two
c    10

我们会发现 two列的值等于20的行全删掉了。
当然你可能也发现了,字符串格式的值需要加单引号,整数啥的直接等于就好了。

就是更新(update)数据呀,不过这也提醒我们要加一条数据独一无二的列,例如id之类的。不过这里只是展示就不加了。我们将第一列的 c修改成 abc,命令如下:

sqlite> update tbl1
   ...> set one='abc'
   ...> where two=10;
sqlite> select * from tbl1;
one  two
abc  10

好啦,这也我们就可以简单的使用sqlite了。一些技巧我会慢慢写成单独的博客的。

希望能帮到有需要的人~

Original: https://blog.csdn.net/qq_33919450/article/details/122911864
Author: zhonguncle
Title: sqlite命令行使用方法

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/815719/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球