SQLite入门

如果学校的数据库课程使用SQLite3,或者零基础入门数据库SQLite3,那么这篇一定能帮到你!

SQLite是一个无服务器的、支持事务(Transaction)的、不需要前置配置的轻量级数据库。

这意味着只需要下载解压后,可以几乎无条件地开始数据增删改查。

SQLite安装

Step1: 从官网(https://www.sqlite.org/download.html)下载您计算机对应版本SQLite工具,选择包含以下工具的文件:

  • 命令行交互界面(the command-line shell)——sqlite3.exe
  • 数据库差异比较&迁移工具(sqldiff)
  • 数据库文件和查询性能工具(sqlite3_analyzer)
  • 远程数据同步工具(sqlite3_rsync)

Step2: 下载好后,找到该压缩包,并解压到文件夹,如“C:\COMP”,使该目录结构如下:

C:\COMP
    sqlite3.exe
    sqldiff.exe
    sqlite3_analyzer.exe
    sqlite3_rsync.exe

Step3: 运行SQLite,验证安装成功,打开方式:

  1. 在该文件夹下进入命令行工具,输入sqlite3
  2. 双击sqlite3.exe

QA:如何在任何文件目录运行SQLite?
将SQLite路径添加到计算机环境变量中

QA:为何打开sqlite后,.read sql文件失败,显示错误信息sqlite3: No such file or directory?
这意味着计算机找到的sqlite3.exe和当前sql文件不在同一个目录下,为了修复这个错误,需要确保以下配置:(1)当前sql文件所在文件夹中,sqlite3.exe不是快捷方式;(2)当前sql文件所在文件夹中,sqlite3.exe是整台电脑中唯一的,或者(仅限添加SQLite环境变量的用户)是系统环境变量指向的。

SQLite命令行支持两种命令,一种是点命令,另一种是SQL命令。前者提供SQLite程序函数调用,以 ”.“ 开始,不以 “;” 结束;后者操作数据库,以 “;” 结束。

SQLite命令

命令 描述
.help 显示消息
.show 显示各种设置的当前值
.databases 列出数据库的名称及其所依附的文件
.read FILENAME 执行 FILENAME 文件中的 SQL
.quit|.exit 退出 SQLite 提示符
.tables ?PATTERN? 列出匹配 LIKE 模式的表的名称
.schema ?TABLE? 显示 CREATE 语句。如果指定了 TABLE 表,则只显示匹配 LIKE 模式的 TABLE 表
.header(s) ON|OFF 开启或关闭头部显示
.import FILE TABLE 导入来自 FILE 文件的数据到 TABLE 表中
.mode MODE 设置输出模式,MODE 可以是(csv, column, html, insert, tabs, tcl)
.output FILENAME 发送输出到 FILENAME 文件

Example1: 查看点命令清单

    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
.crlf ?on|off?           Whether or not to use \r\n line endings
.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
.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
.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
.www                     Display output of the next command in web browser

Example2: 美化输出(示例:显示表头、表格化输出)

    sqlite>.header on
    sqlite>.mode column

Example3-1: 创建/打开数据库,方法一,打开命令行(cmd、bash等)输入

C:\COMP>sqlite3 MyDatabase.db
SQLite version 3.47.0 2024-10-21 16:30:22
Enter ".help" for usage hints.
sqlite>

Example3-2: 创建/打开数据库,方法二,直接双击打开sqlite3.exe输入

    sqlite>.open MyDatabase.db

Example4:在Example3后,查看所有数据库,在SQLite中输入

   sqlite>.databases
   main: C:\COMP\MyDatabases.db r/w

SQL语法

同mysql,网上教程很多,推荐几个自学网站:

  • SQL自学网 http://www.xuesql.cn/
    由浅入深介绍SQL知识,每一个章节都有一个SQL相关知识点并附有相应练习
  • Leetcode、牛客网
    SQL刷题、进阶,每道题后都会有题解与讨论