views:

6984

answers:

2

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.

+2  A: 

If you are looking for a php script see below.

$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
  die('Not connected : ' . mysql_error());
}

// make foo the current db
$db_selected = mysql_select_db('foo', $link);
if (!$db_selected) {
  die ('Cannot use foo : ' . mysql_error());
}
TopPot
Nice and simple. I like it.
lucha libre
+6  A: 
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;
Kirtan
First one good. Second one not so much. You might not have database creation privilege.
Ollie Jones