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.
A simple way to check if a database exists is: SHOW DATABASES LIKE 'dbname'; If database with the name 'dbname' doesn't exist, you get an empty set. If it does exist, you get one row.
In order to do so, simply use the 'if exists' method and select the name of the database from sysdatabases. The code below will drop an existing database if it exists so be careful. An alternate method is to use the db_id to convert the db_name and see if it is null.
After creation, you can look use SELECT DATABASES LIKE 'database_name' When the result contains one entry, you know it has been created.
To access a specific database, type the following command at the mysql> prompt, replacing dbname with the name of the database that you want to access: Copy use dbname; Make sure you do not forget the semicolon at the end of the statement. After you access a database, you can run SQL queries, list tables, and so on.
SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = 'DBName'
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;
A simple way to check if a database exists is:
SHOW DATABASES LIKE 'dbname';
If database with the name 'dbname' doesn't exist, you get an empty set. If it does exist, you get one row.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With