Skip to content

21.4 MySQL

MySQL 是由 Oracle 公司主导开发的开源关系型数据库管理系统(Relational Database Management System,RDBMS)。

MySQL 9.7 是最新长期支持版本,MySQL 8.4 是最新长期支持维护版本。

21.4.1 安装 MySQL 8.4 LTS

使用 pkg 安装:

sh
# pkg install mysql84-server

或使用 ports 编译安装:

sh
# cd /usr/ports/databases/mysql84-server/
# make install clean

查看安装后的说明:

sh
# pkg info -D mysql84-server

21.4.2 安装 MySQL 9.7 LTS

使用 pkg 安装:

sh
# pkg install mysql97-server

或使用 ports 编译安装:

sh
# cd /usr/ports/databases/mysql97-server/
# make install clean

查看安装后的说明:

sh
# pkg info -D mysql97-server

21.4.3 启动服务

安装完成后,需启动 MySQL 服务才能使用。

设置 MySQL 服务开机自启:

sh
# service mysql-server enable

立即启动 MySQL 服务:

sh
# service mysql-server start

21.4.4 登录

服务启动后,可以使用命令行客户端(作为依赖将自动安装)登录 MySQL。根据安装说明,MySQL 8.4、9.7 的默认密码为空,登录时直接按回车即可。

使用 root 用户登录 MySQL 服务器,提示输入密码:

sql
# mysql -uroot -p
Enter password: # 此处直接按回车键
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 8.4.9 Source distribution

Copyright (c) 2000, 2026, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

21.4.5 修改密码

为了数据库安全,首次登录后建议立即修改 root 用户密码。以下命令将数据库的 root 用户密码设置为 SecurePass123!,然后刷新权限,最后退出 MySQL。

sql
mysql> alter user 'root'@'localhost' identified by 'SecurePass123!'; -- 修改 root 用户的密码为 SecurePass123!
Query OK, 0 rows affected (0.01 sec)

mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)

mysql> quit; -- 退出 MySQL 命令行客户端
Bye

重新登录:

sql
# mysql -uroot -p  # 使用 root 用户登录 MySQL,并按提示输入密码
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 9
Server version: 8.4.9 Source distribution

Copyright (c) 2000, 2026, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> show databases; -- 显示当前 MySQL 实例中的所有数据库
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
4 rows in set (0.00 sec)

mysql> quit; -- 退出 MySQL 命令行客户端
Bye

21.4.6 MySQL 配置文件

MySQL 的配置文件结构如下。

sh
/
└── usr/
    └── local/
       └── etc/
           └── mysql/
                ├── my.cnf        # MySQL 配置文件
                └── my.cnf.sample # MySQL 配置文件示例

如需进一步配置 MySQL,可以修改其配置文件。配置文件可以调整数据库的各种参数,如内存使用、连接数等。

MySQL 默认的配置文件模板位于 /usr/local/etc/mysql/my.cnf.sample,实际的默认配置文件位于 /usr/local/etc/mysql/my.cnf(默认内容为空)。

复制 MySQL 示例配置文件为正式配置文件:

sh
# cp /usr/local/etc/mysql/my.cnf.sample /usr/local/etc/mysql/my.cnf

然后根据需要修改 /usr/local/etc/mysql/my.cnf 文件即可。

如需使用自定义的配置文件路径,可在 /etc/rc.conf 文件中写入:

ini
mysql_optfile="/abc/xyz.cnf"