如何检查mysql数据库是否存在

2021-11-20 00:00:00 database mysql exists

是否可以在建立连接后检查(MySQL)数据库是否存在.

Is it possible to check if a (MySQL) database exists after having made a connection.

我知道如何检查数据库中是否存在表,但我需要检查数据库是否存在.如果不是,我必须调用另一段代码来创建它并填充它.

I know how to check if a table exists in a DB, but I need to check if the DB exists. If not I have to call another piece of code to create it and populate it.

我知道这一切听起来有点不雅 - 这是一个快速而肮脏的应用程序.

I know this all sounds somewhat inelegant - this is a quick and dirty app.

推荐答案

SELECT SCHEMA_NAME
  FROM INFORMATION_SCHEMA.SCHEMATA
 WHERE SCHEMA_NAME = 'DBName'

如果您只需要知道一个数据库是否存在以便在尝试创建它时不会出错,只需使用 (From 此处):

If you just need to know if a db exists so you won't get an error when you try to create it, simply use (From here):

CREATE DATABASE IF NOT EXISTS DBName;

相关文章