MYSQL 设置默认数据库

MYSQL set a default database

当我连接我的 MYSQL 时,我每次都必须选择要使用的数据库:

use mysql_crashcourse;

我在连接到 MYSQL

后立即检查时发现 DATABASE() returns 为空
mysql> SELECT DATABASE();
+------------+
| DATABASE() |
+------------+
| NULL       |
+------------+

我的问题是:如何设置默认 MYSQL 数据库,这样我就不需要在每次连接或登录 MYSQL 时都提供数据库信息?

如果您在查询中没有 select 任何其他内容,则 return 值为空。如果你想得到别的东西,你可以这样做:

 mysql> SELECT 1 IS NULL, 1 IS NOT "something";

如果您 log-in 直接从 cli。 在 my.cnf 上创建客户端会话并重新启动 mysql 服务。

注意从本地主机登录的每个 root 用户都将拥有默认数据库。

示例:

root@ergesttstsrv:~# cat /etc/mysql/my.cnf

[client]
host=localhost
user=root
password=
database=gesti

!includedir /etc/mysql/conf.d/
!includedir /etc/mysql/mysql.conf.d/

root@ergesttstsrv:~# service mysql restart

root@ergesttstsrv:~# mysql -u root -p
Enter password:
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 9
Server version: 8.0.25 MySQL Community Server - GPL

Copyright (c) 2000, 2021, 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> select database();
+------------+
| database() |
+------------+
| gesti      |
+------------+
1 row in set (0.00 sec)