SQL C#

Create an SQL Database with Check

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#.

Program.cs

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);
            }
        }
    }
}
 

Output

-1
Press any key to continue . . .
 

Before

Before
 

After

After
 

Second Output

The database catholic already exists.
0
Press any key to continue . . .
 
 

© 2007–2024 XoaX.net LLC. All rights reserved.