SQLite Autoincrement(自动递增),primarykey
概述
sqlite的Autoincrement是一个关键字,用于某一字段设置为自增字段
语法:在创建表时的特定列上使用AUTOINCREMENT关键字实现字段值的自动递增,
create table table_name(
column1 dat1,
column2 dat2,
......
columnN datN,
);
注意:关键字Autoincrement只能由于整形(integer primary key)字段。
primary key 约束
PRIMARY KEY 约束唯一标识数据库表中的每个记录。在一个表中可以有多个 UNIQUE 列,但只能有一个主键。在设计数据库表时,主键是很重要的。主键是唯一的 ID。
我们使用主键来引用表中的行。可通过把主键设置为其他表的外键,来创建表之间的关系。由于"长期存在编码监督",在 SQLite 中,主键可以是 NULL,这是与其他数据库不同的地方。
主键是表中的一个字段,唯一标识数据库表中的各行/记录。主键必须包含唯一值。主键列不能有 NULL 值。
一个表只能有一个主键,它可以由一个或多个字段组成。当多个字段作为主键,它们被称为复合键。
如果一个表在任何字段上定义了一个主键,那么在这些字段上不能有两个记录具有相同的值。
自增代码实例
zgy@zgy-virtual-machine:~/sqlite$ sqlite3 student1.db SQLite version 3.31.1 2020-01-27 19:55:54 Enter ".help" for usage hints. sqlite> .table STU1 sqlite> drop table stu1; sqlite> create table student(id integer autoincrement,name char,sex char,score real); Error: near "autoincrement": syntax error sqlite> create table student(id integer autoincrement not null,name char,sex char,score real); Error: near "autoincrement": syntax error sqlite> create table student(id integer primary key autoincrement not null,name char,sex char,score real); sqlite> drop table student; sqlite> create table student(id integer primary key autoincrement,name char,sex char,score real); sqlite> drop table student; sqlite> create table student(id int primary key autoincrement,name char,sex char,score real); Error: AUTOINCREMENT is only allowed on an INTEGER PRIMARY KEY sqlite> create table student(id integer primary key autoincrement,name char,sex char,score real); sqlite> .schema CREATE TABLE sqlite_sequence(name,seq); CREATE TABLE student(id integer primary key autoincrement,name char,sex char,score real); sqlite> .schema student CREATE TABLE student(id integer primary key autoincrement,name char,sex char,score real); sqlite> insert into student values('zhangsan','m',98.4); Error: table student has 4 columns but 3 values were supplied sqlite> insert into student(name,sex,score) values('zhangsan','m',98.4); sqlite> insert into student(name,sex,score) values('lisi','m',93.5); sqlite> insert into student(name,sex,score) values('wangwu','w',89.5); sqlite> select * from student; 1|zhangsan|m|98.4 2|lisi|m|93.5 3|wangwu|w|89.5 sqlite>
本站文章为和通数据库网友分享或者投稿,欢迎任何形式的转载,但请务必注明出处.
同时文章内容如有侵犯了您的权益,请联系QQ:970679559,我们会在尽快处理。