Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1277637
  • 博文数量: 185
  • 博客积分: 50
  • 博客等级: 民兵
  • 技术积分: 3934
  • 用 户 组: 普通用户
  • 注册时间: 2007-09-11 13:11
个人简介

iihero@ChinaUnix, ehero.[iihero] 数据库技术的痴迷爱好者. 您可以通过iihero AT qq.com联系到我 以下是我的三本图书: Sybase ASE in Action, Oracle Spatial及OCI高级编程, Java2网络协议内幕

文章分类

全部博文(185)

文章存档

2014年(4)

2013年(181)

分类: SQLite/嵌入式数据库

2013-12-19 13:46:03

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的相关创建语句,不再缀述。
阅读(6948) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~