SQL语句基础入门

1.1 创建数据库

Sqlite xxx.db;(注意所有sql语句需要以“;”结尾)

eg: sqlite test.db;

.open xxx.db (打开数据库,该方法也可创建)

 eg: sqlite test.db

1.2 创建表

create table 表名(字段一,字段二,字段三);

eg: create table human (id int ,name text , sex  varchar); 

注意:SQL中的五种数据类型:字符型,文本型,数值型,逻辑型和日期型

1.3 查看表结构

         .schema

1.4 查看表名

        .table

1.5 查看数据存放位置

         .database

1.6 重命名表名

         alter table 旧表名 rename to 新表名;

eg:  alter table human rename to human1;

1.7 增加表字段

         alter table 表名 add column 列名 类型;

eg: alter  table human add column love text;

1.8 删除表

         drop table 表名;

eg: drop table human;

1.9 删除表字段

         a 先复制需要的列名,放入临时列表

                   create table temp as select name,age,sex from human where 1=2;

         b 删除原表

                   drop table human;

         c 重命名临时表为原表

                   alter table temp rename to human;

2 增删改查

2.1  insert into 表名(类型一,类型二,类型三)values(一,二,三);

eg:  insert into human(id,name,age,sex) values(0,’Alice’,22,’man’);

or   insert into human values(0,’Alice’,22,’man’);
2.2  delete from 表名称 where 列名称 = 值

eg:   delete from human where name = ‘Alice’;

2.3  update 表名称 set 列名称 = 新值 where 列名称 = 某值;

eg:  updata human set name = ‘Jim’ where name =’Alice’;

2.4  select 列名称 from 表名称 where 列 运算符 值 (where  指定查询条件)(group by 分组) (order by  asc/desc)

eg:  select name from human where name = ‘Alice’;

3 函数操作

3.1 lower() 将字符串转换为小写

eg: select lower(name) as 小写名字 from human;

3.2 upper() 将字符串转换为大写

eg: select upper(name) as 大写名字 from human;

3.3 avg() 返回某列平均值

eg: select avg(age) as 平均年龄 from human;

3.4 count() 返回某列行数

eg: select count(age) as 当前人数 from human;

3.5 max() 返回某列最大值

eg: select max(age) from human;

or select * from human where age = (select max(age) from human);

3.6 min()返回某列最小值

eg: select min(age) from human;

3.7 sum() 求和

eg: select sum(age) from human;

3.8 desc 降序

eg: select * from human order by age desc;

3.9 asc 升序排序

eg: select * from human order by age asc;

3.10  group by  分组

eg: select sex,count(*) as 人数 from human group by sex;

4 主键,唯一约束 检查约束

4.1主键:primary key 一个表只能有一个主键,是全表的唯一标示符;

4.2唯一约束:unique 一个表可以有多个唯一约束,用来确保某个字段数字的唯一性。

eg: create table student(id int primary key,name text unique,address text unique,grade int);

4.3检查约束: check

eg:create table student1( id int primary key,name text check (name is not null),age int check(age > 0 or age < 100) );

5事物 保持数据的一致性和可恢复性  

5.1 begin;标记事物的开始

5.2 commit;确认提交

5.3rollback; 撤回到原来版本(当使用commit命令后就不可恢复)

5.4 save 设置事物的保存点,只回滚到这里

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值