Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if mysql database exists

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.

like image 654
Ankur Avatar asked May 08 '09 09:05

Ankur


People also ask

How do you check database are exist in MySQL?

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.

How do I check if a SQL Server database exists?

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.

How do you verify if the database is created successfully?

After creation, you can look use SELECT DATABASES LIKE 'database_name' When the result contains one entry, you know it has been created.

How do I open MySQL database?

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.


2 Answers

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; 
like image 90
Kirtan Avatar answered Sep 16 '22 17:09

Kirtan


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.

like image 32
Ruben Konig Avatar answered Sep 16 '22 17:09

Ruben Konig