MySQL常用终端命令
1. 安装命令
apt-get install mysql-server mysql-client libmysqlclient-dev
2. 服务管理
/etc/init.d/mysql start/stop/restart # 启动/停止/重启服务
mysqladmin -u root -p shutdown # 关闭服务
netstat -tap | grep mysql # 检查服务状态
ps -ef | grep mysql # 查看进程
3. 连接与退出
mysql -u root -p # 基本连接
mysql -h localhost -P 3306 -u root -p # 指定主机和端口
quit; \q # 退出(MySQL交互模式下)
4. 数据库操作
show databases; # 显示所有数据库
create database dbname; # 创建数据库
use dbname; # 选择数据库
drop database dbname; # 删除数据库
select database(); # 查看当前数据库
5. 数据表操作
show tables; # 显示所有表
create table tab (id int primary key auto_increment, name varchar(8), pwd varchar(8)); # 创建表
describe tab; show columns from tab; # 查看表结构
drop table tab; # 删除表
alter table oldname rename to newname; # 修改表名
alter table tab add sex varchar(8); # 添加字段
alter table tab drop sex; # 删除字段
alter table tab modify name varchar(20) not null; # 修改字段属性
alter table tab change oldcol newcol varchar(40); # 修改字段名
alter table tab drop primary key; # 去掉主键
alter table tab add primary key (name); # 添加主键
6. 数据操作
insert into tab (name, pwd) values ('admin', '123456'); # 插入数据
select * from tab; # 查询所有数据
select * from tab where name='admin'; # 条件查询
update tab set pwd='654321' where name='admin'; # 更新数据
delete from tab where name='admin'; # 删除数据
7. 用户与权限
create user 'user'@'localhost' identified by 'pwd'; # 创建用户
grant all privileges on *.* to 'user'@'localhost' with grant option; # 授予权限
flush privileges; # 刷新权限
show grants for 'user'@'localhost'; # 查看权限
revoke all privileges on *.* from 'user'@'localhost'; # 撤销权限
drop user 'user'@'localhost'; # 删除用户
8. 其他命令
select version(); # 查看版本
select now(); # 查看当前时间
select user(); # 查看当前用户
select database(); # 查看当前数据库