1. 问题提出
有人问,在sqlite中怎么用sql语句得到一个表的列定义语句。第一反应,可能就是用.schema
可是这是sqlite的shell命令行。
使用代码,好像得不到结果。
幸好,sqlite它有比较特殊的系统表:
sqlite_master
sqlite_temp_master
这两张系统表的表结构完全相同,如下所示:
- sqlite> .schema sqlite_master
- CREATE TABLE sqlite_master (
- type text,
- name text,
- tbl_name text,
- rootpage integer,
- sql text
- );
- sqlite> .schema sqlite_temp_master
- CREATE TEMP TABLE sqlite_temp_master (
- type text,
- name text,
- tbl_name text,
- rootpage integer,
- sql text
- );
2. 实例说明
我们通过实例来说明,看看.schema相当于什么样的sql语句执行结果:
- sqlite> create table t(id int);
- sqlite> create temporary table t(id int, col2 varchar(32));
- sqlite> insert into t values(1);
- Error: table t has 2 columns but 1 values were supplied
- sqlite> drop table t;
- sqlite> .tables
- t
- sqlite> insert into t values(1);
- sqlite> create temporary table t(id int, col2 varchar(32));
- sqlite> insert into t values(2, 'wang');
- sqlite> .schema t
- CREATE TABLE t(id int);
- CREATE TABLE t(id int, col2 varchar(32));
- sqlite> select sql from sqlite_master where tbl_name='t';
- CREATE TABLE t(id int)
- sqlite> select sql from sqlite_temp_master where tbl_name='t';
- CREATE TABLE t(id int, col2 varchar(32))
- sqlite> select sql from sqlite_master where tbl_name='t' and type='table' union all select sql from
- sqlite_temp_master where tbl_name='t' and type='table';
- CREATE TABLE t(id int)
- CREATE TABLE t(id int, col2 varchar(32))
- sqlite>
创建完以后,在插入数据时,它优先认可临时表。
当我们运行.schema t时,会把两张表都列出来。
然后通过查询sqlite_master中的sql字段可以得到非临时表的建表信息,sqlite_temp_master中的sql字段能得到临时表的信息。两者的union就会得到所有表的信息。
所以:
.schema
等价于:
- select sql from sqlite_master where tbl_name='' and type='table' union all select sql from
- sqlite_temp_master where tbl_name='' and type='table';
值得一提的是,当type='index'时,还可以得到index的相关创建语句,不再缀述。