This C# program demonstrates how to create an SQL database after checking for an existing database with the same name for Microsoft SQL in C#.
using System;
using System.Data.SqlClient;
namespace CreateDatabase {
class Program {
static void Main(string[] args) {
Console.WriteLine(CreateDatebase("catholic"));
}
public static int CreateDatebase(string sDatabase) {
// The using block ensures that the connection is closed when it exits this block.
using (SqlConnection qConnection = new SqlConnection(
@"Server=localhost\SQLEXPRESS01;Trusted_Connection=True;")) {
qConnection.Open();
// Check whether the database exists
if (DatabaseExists(qConnection, sDatabase)) {
Console.WriteLine("The database " + sDatabase + " already exists.");
return 0;
} else {
// Create a command to create a database
SqlCommand qCommand = qConnection.CreateCommand();
qCommand.CommandText = "CREATE DATABASE " + sDatabase;
return qCommand.ExecuteNonQuery();
}
}
}
public static bool DatabaseExists(SqlConnection qConnection, string sDatabase) {
using (var qCommand = new SqlCommand(@"SELECT db_id('"+sDatabase +"')", qConnection)) {
return (qCommand.ExecuteScalar() != DBNull.Value);
}
}
}
}
-1 Press any key to continue . . .
The database catholic already exists. 0 Press any key to continue . . .
© 20072025 XoaX.net LLC. All rights reserved.