欢迎投稿

今日深度:

使用SQL语句获取SQLite中的表定义,sqlsqlite

使用SQL语句获取SQLite中的表定义,sqlsqlite


1. 问题提出

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

可是这是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>
我们看到,创建了两个表,都叫t, 一个是临时表,一个是非临时的。

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

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

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

所以:

.schema <t>

等价于:

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';

值得一提的是,当type='index'时,还可以得到index的相关创建语句,不再缀述。

www.htsjk.Com true http://www.htsjk.com/SQLite/30872.html NewsArticle 使用SQL语句获取SQLite中的表定义,sqlsqlite 1. 问题提出 有人问,在sqlite中怎么用sql语句得到一个表的列定义语句。第一反应,可能就是用.schema tablename 可是这是sqlite的shell命令行。 使用...
相关文章
    暂无相关文章
评论暂时关闭