1. 问题提出

有人问,在sqlite中怎么用sql语句得到一个表的列定义语句。第一反应,可能就是用.schema

可是这是sqlite的shell命令行。

使用代码,好像得不到结果。

幸好,sqlite它有比较特殊的系统表:

sqlite_master

sqlite_temp_master

这两张系统表的表结构完全相同,如下所示:


  1. sqlite> .schema sqlite_master  
  2. CREATE TABLE sqlite_master (  
  3.   type text,  
  4.   name text,  
  5.   tbl_name text,  
  6.   rootpage integer,  
  7.   sql text  
  8. );  
  9. sqlite> .schema sqlite_temp_master  
  10. CREATE TEMP TABLE sqlite_temp_master (  
  11.   type text,  
  12.   name text,  
  13.   tbl_name text,  
  14.   rootpage integer,  
  15.   sql text  
  16. );  



2. 实例说明

我们通过实例来说明,看看.schema相当于什么样的sql语句执行结果:



  1. sqlite> create table t(id int);  
  2. sqlite> create temporary table t(id int, col2 varchar(32));  
  3. sqlite> insert into t values(1);  
  4. Error: table t has 2 columns but 1 values were supplied  
  5. sqlite> drop table t;  
  6. sqlite> .tables  
  7. t  
  8. sqlite> insert into t values(1);  
  9. sqlite> create temporary table t(id int, col2 varchar(32));  
  10. sqlite> insert into t values(2, 'wang');  
  11. sqlite> .schema t  
  12. CREATE TABLE t(id int);  
  13. CREATE TABLE t(id int, col2 varchar(32));  
  14. sqlite> select sql from sqlite_master where tbl_name='t';  
  15. CREATE TABLE t(id int)  
  16. sqlite> select sql from sqlite_temp_master where tbl_name='t';  
  17. CREATE TABLE t(id int, col2 varchar(32))  
  18. sqlite> select sql from sqlite_master where tbl_name='t' and type='table' union all select sql from  
  19. sqlite_temp_master where tbl_name='t' and type='table';  
  20. CREATE TABLE t(id int)  
  21. CREATE TABLE t(id int, col2 varchar(32))  
  22. sqlite>  
我们看到,创建了两个表,都叫t, 一个是临时表,一个是非临时的。


创建完以后,在插入数据时,它优先认可临时表。

当我们运行.schema t时,会把两张表都列出来。

然后通过查询sqlite_master中的sql字段可以得到非临时表的建表信息,sqlite_temp_master中的sql字段能得到临时表的信息。两者的union就会得到所有表的信息。

所以:

.schema

等价于:


  1. select sql from sqlite_master where tbl_name='' and type='table' union all select sql from  
  2. sqlite_temp_master where tbl_name='' and type='table';  

值得一提的是,当type='index'时,还可以得到index的相关创建语句,不再缀述。
09-01 21:30
查看更多