$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());
}
if [[ ! -z "`mysql -qfsBe "SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME='db'" 2>&1`" ]];
then
echo "DATABASE ALREADY EXISTS"
else
echo "DATABASE DOES NOT EXIST"
fi
function does_db_exist {
local db="${1}"
local output=$(mysql -s -N -e "SELECT schema_name FROM information_schema.schemata WHERE schema_name = '${db}'" information_schema)
if [[ -z "${output}" ]]; then
return 1 # does not exist
else
return 0 # exists
fi
}
另一种选择是尝试使用数据库。注意,这也检查权限:
if mysql "${db}" >/dev/null 2>&1 </dev/null
then
echo "${db} exists (and I have permission to access it)"
else
echo "${db} does not exist (or I do not have permission to access it)"
fi
IF EXISTS (SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = N'YourDatabaseName')
BEGIN
-- Database exists, so do your stuff here.
END