Linux MySQL 基本操作
Linux MySQL 基本操作
连接到MySQL
连接到本机上的MySQL
mysql -u username -p 回车后输入密码
AI 代码解读
连接到远程主机上的MySQL
mysql -h主机地址 --port=端口号 -u username -ppassword
AI 代码解读
开启远程访问权限
授权法
GRANT ALL PRIVILEGES ON *.* TO 'username'@'%' IDENTIFIED BY 'youpassword' WITH GRANT OPTION;
flush privileges;
AI 代码解读
%:表示在任何客户端机器上都能远程访问,也可指定具体ip。
username:表示能以username用户登录到MySQL服务器。
ALL PRIVILEGES :表示赋予所有权限
改表法
use mysql;
update user set host='%' where user='username';
AI 代码解读
查看授权
show grants for test;
select * from mysql.user where user='test'\G;
AI 代码解读
修改root用户密码
使用mysqladmin
mysqladmin -uroot password "newpassword"
AI 代码解读
如果root用户已经设置过密码,则
mysqladmin -uroot password oldpassword "newpassword"
AI 代码解读
修改user表
use mysql;
update user set password=password("newpassword") where user='root';
flush privileges;
AI 代码解读
alter语句
flush privileges;
AI 代码解读
set password语句
set password=password("newpassword")
flush privileges;
AI 代码解读
root忘记密码破解方法
- 停止mysql服务
service mysqld stop
AI 代码解读
- 用以下命令启动mysql,以不检查权限的方式启动
mysqld_safe --skip-grant-tables &
AI 代码解读
- 使用空密码方式使用root用户登录mysql
mysql -uroot -p 回车
AI 代码解读
- 修改root用户的密码
use mysql
update user set password=password("newpassword") where user='root';
flush privileges;
quit
AI 代码解读
- 重启mysql服务
service mysqld restart
AI 代码解读
- root用户使用新密码进行登录
- mysql -uroot -p 回车输入新密码、
数据库
- 显示数据库
show databases;
AI 代码解读
- 创建数据库
create database db_name;
AI 代码解读
- 选择数据库
use db_name;
AI 代码解读
- 删除数据库
drop database db_name;
AI 代码解读
表
- 创建表
create table scutech (id int not null AUTO_INCREMENT,name varchar(20) not null,tel char(11),current_time timestamp default current_timestamp,primary key (id));
AI 代码解读
- 显示数据库中的表
show tables;
AI 代码解读
- 查看表结构
desc table_name;
AI 代码解读
- 查看表详细结构语句
show create table table_name;
AI 代码解读 - 向表中插入记录
insert into scutech(name) values("zhou");
AI 代码解读
将查询到的结果插入表中
insert into table_name(属性1,属性2,...,属性n) select 属性列表 from 表名2 where 条件表达式
AI 代码解读
- 查看表中记录
select * from scutech;
AI 代码解读
- 计算表中记录数
select count(*) from scutech;
AI 代码解读
- 更新表中记录
update scutech set name="zhang" where id=1;
AI 代码解读
- 删除表中记录
delete from scutech where id=1;
AI 代码解读
修改表结构
- 重命名表
alter table scutech rename newscutech;
AI 代码解读
ALTER TABLE 表名 ADD 字段名 1 数据类型 [完整性约束条件] [FIRST|AFTER 属性名 2];
alter table scutech add t1 char(10);
alter table scutech add sex enum ("boy","girl") default "boy" after name ;
AI 代码解读
- 修改字段名change (原字段名 新字段名 类型)
ALTER TABLE 表名 CHANGE 原字段名 新字段名 新数据类型;
alter table scutech change tel phone_num char(11);
AI 代码解读
- 删除字段drop
ALTER TABLE 表名 DROP 字段名;
alter table scutech drop name,drop sex;
AI 代码解读
- 修改字段类型modify,不能与字段已存储的数据冲突
ALTER TABLE 表名 MODIFY 字段名 数据类型;
alter table scutech modify sex enum("boy","girl","no") not null default "no";
AI 代码解读
- 修改表的存储引擎
alter table scutech engine=innodb;
AI 代码解读 - 删除表的外键约束
alter table table_name drop foreign key 外键名;
AI 代码解读
数据库引擎
show engines \G
show variables like '%engine%';
AI 代码解读
innodb引擎
最常用,支持事务,回滚,自增,外键
表结构存在.frm 文件中
数据和索引存在表空间中
读写效率稍差,占用空间大
myisam
表结构存在.frm 文件中
.myd 存储数据
.myi 存储索引
快速,占空间小,丌支持事务和幵収