private static bool _DatabaseExists(DbProviderFactory provider, string connectionString, string providerName) { string dbName, cmdText = null; string connStr = _StripDbName(connectionString, providerName, out dbName); try { log.DebugFormat( CultureInfo.InvariantCulture, "Checking if database '{0}' exists, with provider: {1}, and connectionString: {2}", dbName, providerName, connStr); if (providerName == SQLiteProvider) { if (dbName.ToUpperInvariant() == ":MEMORY:") { return false; } else { return File.Exists(dbName); } } if (providerName == SqlCe || providerName == Firebird) { return File.Exists(dbName); } switch (providerName) { case MsSqlProvider: cmdText = string.Format(CultureInfo.InvariantCulture, "select COUNT(*) from sys.sysdatabases where name=\'{0}\'", dbName); break; case MySqlProvider: cmdText = string.Format( CultureInfo.InvariantCulture, @"SELECT COUNT(*) FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '{0}'", dbName); break; case OracleDataProvider: cmdText = "SELECT 1 FROM DUAL"; break; case PostgreSQLProvider: cmdText = string.Format( CultureInfo.InvariantCulture, "select count(*) from pg_catalog.pg_database where datname = '{0}'", dbName); break; default: throw new NotSupportedException(string.Format( CultureInfo.InvariantCulture, "Provider {0} is not supported", providerName)); } object ret = provider.ExecuteScalar(connStr, cmdText); int count = ret == null ? 0 : Convert.ToInt32(ret, CultureInfo.InvariantCulture); if (count > 0) { return true; } } catch (NotSupportedException) { throw; } catch (Exception ex) { log.Error("Database connection failed", ex); } log.DebugFormat(CultureInfo.InvariantCulture, "Database '{0}' does not exists", dbName); return false; }