공부/c#
DB 확인 후 없으면 DB생성
령선
2023. 4. 4. 13:08
반응형
static void CreateDatabase()
{
// Check if database exists
bool dbExists = false;
string dbName = "db_name";
try
{
using (NpgsqlConnection connection = new NpgsqlConnection(connectionString))
{
connection.Open();
using (NpgsqlCommand command = new NpgsqlCommand($"SELECT 1 FROM pg_database WHERE datname='{dbName}'", connection))
{
object result = command.ExecuteScalar();
dbExists = result != null;
}
}
if (!dbExists)
{
// Create database
using (NpgsqlConnection connection = new NpgsqlConnection(connectionString))
{
connection.Open();
using (NpgsqlCommand command = new NpgsqlCommand($"CREATE DATABASE {dbName}", connection))
{
command.ExecuteNonQuery();
}
connection.Close();
}
}
else
{
}
}
catch
{
}
}
DB에 SELECT로 DB가 있는지 확인 후 없으면 해당 DB생성
위 코드는 Postgresql를 사용했음
반응형