SQLite 创建表


sqlite 的 create table 语句用于在任何给定的数据库创建一个新表。创建基本表,涉及到命名表、定义列及每一列的数据类型。

 

1. 语法

create table 语句的基本语法如下:

create table database_name.table_name(
   column1 datatype  primary key(one or more columns),
   column2 datatype,
   column3 datatype,
   .....
   columnn datatype,
);

create table 是告诉数据库系统创建一个新表的关键字。create table 语句后跟着表的唯一的名称或标识。您也可以选择指定带有 table_name 的 database_name。

 

2. 范例

下面是一个范例,它创建了一个 company 表,id 作为主键,not null 的约束表示在表中创建纪录时这些字段不能为 null:

sqlite> create table company(
   id int primary key     not null,
   name           text    not null,
   age            int     not null,
   address        char(50),
   salary         real
);

让我们再创建一个表,我们将在随后章节的练习中使用:

sqlite> create table department(
   id int primary key      not null,
   dept           char(50) not null,
   emp_id         int      not null
);

您可以使用 sqlite 命令中的 .tables 命令来验证表是否已成功创建,该命令用于列出附加数据库中的所有表。

sqlite>.tables
company     department

在这里,可以看到我们刚创建的两张表 company、 department。

您可以使用 sqlite .schema 命令得到表的完整信息,如下所示:

sqlite>.schema company
create table company(
   id int primary key     not null,
   name           text    not null,
   age            int     not null,
   address        char(50),
   salary         real
);

下一节:sqlite 删除表

sqlite教程

相关文章