简体   繁体   中英

How can I get the length of the name of each MySQL database?

I am trying to mimic the output of show databases; using java. I want to output something exactly or very similar to this:

+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
| test               |
+--------------------+

My first idea was to figure out the maximum length of all the databases names before I can start printing the output. However, I am not sure how I can do that.

I tried select max(length(show databases)); which is not valid syntax. I did find that I can use all the tables and run select length(database()); to find the length of the name, but I believe that is not what mysql does to output the results.

Is there another approach to printing the output? Thanks!

SHOW DATABASES is a standalone command and cannot be used as argument as you did it.

With this command you get the information you need:

SELECT MAX(LENGTH(SCHEMA_NAME)) FROM information_schema.schemata;

See also MySQL Documentation

You have to query the information schema table directly. Try this

mysql> SELECT DISTINCT(table_schema), length(table_schema) from 
information_schema.tables;

+--------------------+----------------------+
| table_schema       | length(table_schema) |
+--------------------+----------------------+
| information_schema |                   18 |
| json               |                    4 |
| mysql              |                    5 |
| performance_schema |                   18 |
| sys                |                    3 |
+--------------------+----------------------+
5 rows in set (0.00 sec)

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