在 CentOS 7 上查看和管理 MySQL 数据库,可以通过以下详细步骤进行:
一、安装 MySQL
1. 使用 yum 源方式安装 MySQL
(1)卸载系统自带的 MariaDB:
sudo rpm qa | grep mariadb sudo rpm e nodeps mariadblibs5.5.681.el7.x86_64
(2)下载并安装 MySQL Yum 源:
wget http://dev.mysql.com/get/mysql57communityreleaseel711.noarch.rpm sudo yum localinstall mysql57communityreleaseel711.noarch.rpm
(3)安装 MySQL:
sudo yum install mysqlserver
(4)启动 MySQL:
sudo systemctl start mysqld
(5)获取临时密码:
sudo grep 'temporary password' /var/log/mysqld.log
(6)登录并修改密码:
mysql uroot p ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_password'; FLUSH PRIVILEGES;
2. 使用本地 tar 文件方式安装 MySQL
(1)下载 MySQL 安装包:
wget https://cdn.mysql.com//Downloads/MySQL8.0/mysql8.0.29.tar.gz tar xzvf mysql8.0.29.tar.gz cd mysql8.0.29
(2)编译和安装:
cmake \ DCMAKE_INSTALL_PREFIX=/usr/local/mysql \ DDEFAULT_CHARSET=utf8mb4 \ DDEFAULT_COLLATION=utf8mb4_unicode_ci \ DWITH_EXTRA_CHARSETS=all \ DWITH_MYISAM_STORAGE_ENGINE=1 \ DWITH_INNOBASE_STORAGE_ENGINE=1 \ DWITH_PARTITION_STORAGE_ENGINE=1 \ DWITH_READLINE=1 \ DWITH_ZLIB=system \ DWITH_LIBWRAP=0 \ DWITH_DEBUG=0 \ DENABLED_LOCAL_INFILE=1 \ DWITH_SSL=system \ DWITH_EMBEDDED_SERVER=1 \ DWITH_PLUGIN_DIR="/usr/local/mysql/lib/plugin" \ . make j $(nproc) sudo make install
(3)配置和启动 MySQL:
sudo chown R mysql:mysql /usr/local/mysql sudo /usr/local/mysql/bin/mysqld initialize user=mysql sudo /usr/local/mysql/bin/mysqld_safe user=mysql &
(4)创建 systemd 服务文件:
sudo cat > /etc/systemd/system/mysqld.service <<EOF [Unit] Description=MySQL Server After=network.target [Service] User=mysql Group=mysql ExecStart=/usr/local/mysql/bin/mysqld_safe Restart=always RestartSec=10 [Install] WantedBy=multiuser.target EOF
(5)启用并启动 MySQL 服务:
sudo systemctl enable mysqld sudo systemctl start mysqld
(6)登录并设置 root 密码:
sudo /usr/local/mysql/bin/mysql u root ALTER USER 'root'@'localhost' IDENTIFIED BY 'your_password'; FLUSH PRIVILEGES; EXIT;
二、管理 MySQL 数据库
1. 登录 MySQL
mysql u root p
输入密码后即可进入 MySQL 控制台。
2. 创建数据库和用户
CREATE DATABASE mydatabase; CREATE USER 'myuser'@'localhost' IDENTIFIED BY 'password'; GRANT ALL PRIVILEGES ON mydatabase.* TO 'myuser'@'localhost'; FLUSH PRIVILEGES;
3. 查看所有数据库
SHOW DATABASES;
4. 查看某个数据库中的所有表
USE mydatabase; SHOW TABLES;
5. 查看表结构
DESCRIBE tablename;
6. 插入数据
INSERT INTO tablename (column1, column2) VALUES ('value1', 'value2');
7. 查询数据
SELECT * FROM tablename;
8. 更新数据
UPDATE tablename SET column1 = 'newvalue' WHERE condition;
9. 删除数据
DELETE FROM tablename WHERE condition;
三、常见问题及解决方案
Q1: 如何更改 MySQL 的端口号?
A1: 编辑my.cnf
配置文件,找到[mysqld]
部分,修改port
参数。
[mysqld] port = 33066
保存后重启 MySQL 服务:
sudo systemctl restart mysqld
Q2: 如何远程访问 MySQL?
A2: 确保防火墙允许 MySQL 端口通过,登录 MySQL,为远程用户授予权限:
GRANT ALL PRIVILEGES ON *.* TO 'myuser'@'%' IDENTIFIED BY 'password'; FLUSH PRIVILEGES;
确保my.cnf
中的bindaddress
设置为0.0.0.0
,以允许远程连接:
[mysqld] bindaddress = 0.0.0.0
保存后重启 MySQL 服务。