SQL数据操作

来源:互联网 发布:鸡尾酒工具推荐 知乎 编辑:程序博客网 时间:2024/06/05 13:30
status;——查看数据库相关信息
set names utf8;
set character_set_database=utf8;——设置数据库的编码
show create database 表名;——查看建库的编码
show create table 库名;——查看建表的编码
create database 库名 character set utf8;——创建库并且设置编码
alter database 库名 default character set utf8;——改变已建数据库的编码

一.访问数据库
DBMS——DB
1.连接数据库
mysql -u 用户名 -p
输入密码

2.退出数据库
exit;
quit;

3.查看DB
show databases;

4.创建DB
create database 库名;

5.删除DB
drop database 库名;

6.选择数据库
use 库名;

7.查看当前打开的数据库
select database();


8.查看表
show tables;

二.创建表
1.创建表
create table user(
    username varchar(20),
    password varchar(30),
    email varchar(30),
    mobile varchar(20)
);

2.查看表结构
desc 表名;

3.删除表
drop table 表名;

4.修改表
alter table 表名 rename 新表名;
alter table 表名 add 字段名 字段类型;——追加字段(列)
alter table 表名 modify 字段名 新字段类型[是否允许非空];——修改字段属性(列)
alter table 表名 change 原名 新名 新字段属性;
alter table 表名 drop 字段名;——删除字段(列)

5.增加用户
insert into user(username,password) values('linsa','123');
——当省略字段列表时,表示要给所有字段,按键表时的顺序赋值
insert into user values('tiancheng','123','tiancheng@qq.com',null,'M','花果山');

6.查询用户
select*from user;
——指定查询范围
select username,password from user;
——在显示给字段取别名
select username as 用户名,password as 密码 from user;
select username as NAME,password as PWD from user;
——在查询时增加筛选条件
select*from user where sex='M';
select*from user where sex='M' and username='linsa';
select*from user where email is null;
select*from user where email is not null;

7.修改用户
update user set email='ts@qq.com',mobile='110' where username='linsa';

8.删除用户
delete from user;
delete from user where username='linsa';

9.完善用户表
——所有的表都增加主键字段,主键是唯一的,一般会自增长。
——很多表都增加时间字段,记录一条数据创建的时间。
create table user(
    id int auto_increment primary key,
    username varchar(20),
    password varchar(30),
    email varchar(30),
    mobile varchar(20),
    create_time timestamp
);

create table user(
    id int auto_increment,
    username varchar(20),
    password varchar(30),
    email varchar(30),
    mobile varchar(20),
    create_time timestamp,
    primary key(id)
);

——增加数据(若主键重复,则报错)
insert into user values(null,'tiancheng','123','null,null,now());