python查询数据库语句_Python学习—数据库篇之SQL语句⼀、数据库级别
1.显⽰数据库
show databases;
默认数据库:
mysql - ⽤户权限相关数据
test - ⽤于⽤户测试数据
information_schema - MySQL本⾝架构相关数据
2.创建数据库
# utf-8(推荐使⽤)CREATE DATABASE 数据库名称 DEFAULTCHARSET utf8 COLLATE utf8_general_ci;
# gbkCREATE DATABASE 数据库名称 DEFAULT CHARACTER SET gbk COLLATE gbk_chinese_ci;
3.删除数据库
drop database 数据库名称;
4.使⽤数据库
use 数据库名称;
⼆、表级别
1.显⽰表
show tables; ---显⽰表
desc 表名; ---显⽰表字段
2.创建表
create table表名(
列名 类型 是否可以为空,
列名 类型 是否可以为空
)
ENGINE=InnoDB DEFAULT CHARSET=utf8--InnoDB为数据库引擎的⼀种,⽀持事务操作
是否可空,null表⽰空,⾮字符串not null -不可空null - 可空
是否可以为空
创建列时可以指定默认值,当插⼊数据时如果未主动设置值,则⾃动添加默认值create tabletb1(
nidint not null defalut 2,
numint not null)
默认值
⾃增,如果为某列设置⾃增列,插⼊数据时⽆需设置此列,默认将⾃增(表中只能有⼀个⾃增列)create tabletb1(
nidint not null auto_increment primary key,
numint null)
或create tabletb1(
nidint not nullauto_increment,
numint null,index(nid)
)
注意:1、对于⾃增列,必须是索引(含主键)。2、对于⾃增可以设置步长和起始值
show session variableslike 'auto_inc%';set session auto_increment_increment=2;set session auto_increment_offset=10; shwo global variableslike 'auto_inc%';set global auto_increment_increment
=2;set global auto_increment_offset=10;
⾃增
主键,⼀种特殊的唯⼀索引,不允许有空值,如果主键使⽤单个列,则它的值必须唯⼀,如果是多列,则其组合必须唯⼀。
主键的好处:约束,加速查create tabletb1(
nidint not null auto_increment primary key,
numint null)
或create tabletb1(
nidint not null,
numint not null,primary key(nid,num)
)
主键
外键,⼀个特殊的索引,只能是指定内容
creattablecolor(
nidint not null primary key,
namechar(16) not null)create tablefruit(
nidint not null primary key,
smtchar(32) null,
color_idint not null,constraint fk_cc foreign key (color_id) referencescolor(nid)
)
外键
外键⽰例:创建⼀张学⽣信息表和⼀张班级信息表,将学⽣表中的class_no和班级表中的nid相关联
建⽴外键约束
相当于将学⽣表中的class_no和班级表中的nid约束起来
当再向student表中插⼊数据时,如果class_no不在class表的nid的值域内,则报错
3.删除表
drop table 表名; ---直接删除表
delete from 表名; ---清空表内容
truncate table 表名; ---清空表内容,速度快,有⾃增时清空表后插⼊数据会重新开始编号4.查询表
select * from 表名; ----查询表内容
5.修改表
添加列:alter table 表名 add列名 类型
删除列:alter table 表名 drop column列名
修改列:alter table 表名 modify column 列名 类型; --类型
alter table 表名 change 原列名 新列名 类型; --列名,类型
添加主键:alter table 表名 add primary key(列名);
删除主键:alter table 表名 drop primary key;alter table 表名 modify 列名 int, drop primary key;
添加外键:alter table 从表 add constraint 外键名称(形如:FK_从表_主表) foreign key 从表(外键字段) references主表(主键字段);删除外键:alter table 表名 drop foreign key外键名称
修改默认值:ALTER TABLE testalter_tbl ALTER i SET DEFAULT 1000;
删除默认值:ALTER TABLE testalter_tbl ALTER i DROP DEFAULT;
三、表内容级别
1.增
--向表中插⼊⼀条数据
varchar2最大长度insert into 表 (列名,列名...) values (值,值,值...)
--向表中插⼊多条数据
insert into 表 (列名,列名...) values (值,值,值...),(值,值,值...)
--将另⼀个表中的数据插到其他表中,对应列的数据类型要⼀样或者可以转换
insert into 表1 (列名,列名...) select 列名,列名... from 表2
2.删
--删除整张表
delete from 表
--条件删除,where后⾯可以跟判断条件
delete from 表 where nid=1 and name='h'
3.改
update 表 set name = 'alex' where nid>1
4.查
select * from 表
select * from 表 where id > 1
--as的作⽤是可以将原来的表头以定义的字段命名
select nid,name,sex as gender from 表 where id > 1

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。