数据库
创建
create database if not exists db_name default charset utf8mb4 collate utf8mb4_general_ci;
数据库名字不能超64字符,包含特殊字符的名字或者是全部由数字或保留字组成的名字必须用单引号包起来。
if not exists 的使用强制在不存在数据库的情况下执行命令。
选择使用
use db_name;
删除
drop database if exists db_name;
if exists 的使用可以避免删除不存在的数据库时出现的错误信息
导出
# 导出数据库db_name中的全部表
mysqldump -uroot -p --default-character-set=utf8 db_name > db_name.sql
# 导出数据库db_name中的table_name1和table_name2
mysqldump -uroot -p db_name table_name1 table_name2 > db_name.sql
导入
# 选择数据库
use db_name;
# 导入数据
source db_name.sql
用户
创建
create user user_name@localhost identified by 'user_pwd';
OR
create user user_name@'%' identified by 'user_pwd';
授权数据库
全部权限
grant all privileges on db_name.* to user_name@localhost;
flush privileges;
此user_name用户只可在localhost使用
部分权限
grant select,insert,update,delete on db_name.* to user_name@'%' identified by 'user_password';
flush privileges;
给用户授权某表
grant select,insert,update on db_name.table_name to user_name@'%';
flush privileges;
给用户授权视图
查看视图的权限
grant show view on db_name.view_name to user_name@'%';
flush privileges;
删除用户权限
revoke all privileges on db_name.* from user_name@localhost;
flush privileges;
修改用户密码
use mysql
update user set Password=password('newpassword') where User='user_name';
flush privileges;
OR
update mysql.user set password=password('newpassword') where User='test1' and Host='localhost';
flush privileges;
删除用户
delete from user where user='user_name' and host='localhost';
flush privileges;
数据表
更新字段名称
ALTER TABLE table_name CHANGE `old_col_name` `new_col_name` CHAR(16) DEFAULT NULL;
old_col_name:原字段名
new_col_name:更新后的字段名
只更新字段类型
ALTER TABLE table_name MODIFY `col_name` INT(11) DEFAULT 0;
更新后字段:col_name的类型为: int(11) default 0;
添加字段
ALTER TABLE table_name ADD COLUMN `new_col_name` INT(11);
新添加的字段是:
new_col_name
:
删除字段
ALTER TABLE table_name DROP COLUMN `col_name`;
要删除的字段是:
appid_id
;
按条件查询数据库的表名
必须有访问information_schema数据库的权限
查询表和视图
SELECT * FROM TABLES t WHERE t.table_schema='db_name';
db_name是数据库名
只查询表
SELECT * FROM TABLES t WHERE t.table_schema='db_name' AND t.table_name LIKE 't_%';
db_name是数据库名
t_是名表的前缀