简体   繁体   中英

MYSQL set a default database

When I connect my MYSQL , I have to choose database to use everytime using :

use mysql_crashcourse;

I noticed the DATABASE() returns null when I check it right after I connect to MYSQL

mysql> SELECT DATABASE();
+------------+
| DATABASE() |
+------------+
| NULL       |
+------------+

My question is : how can I set a default MYSQL database ,so that I don't need to provide database info each time I connect or login to MYSQL ?

If you log-in directly from cli. Create a client session on my.cnf and restart mysql service.

Note every root user logged from localhost will have the default database.

Example:

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)

If you do not select anything else in the query, the return value is null. If you want to get anything else, you can do for example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM