SQL C#

Check Database Existence

This C# program demonstrates how to check for the existence of an SQL database for Microsoft SQL in C#.

Program.cs

using System;
using System.Data.SqlClient;

namespace CheckForDatabase {
    class Program {
        static void Main(string[] args) {
            // 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();
                string[] saDatabases = {"homeschool", "xoax", "christian", "math", "catholic" };
                // Run through the array of database names and check each one.
                foreach (string sDatabase in saDatabases) {
                    if (DatabaseExists(qConnection, sDatabase)) {
                        Console.WriteLine("The database " + sDatabase + " exists.");
                    } else {
                        Console.WriteLine("The database " + sDatabase + " does not exist.");
                    }
                }
            }
        }

        public static bool DatabaseExists(SqlConnection qConnection, string sDatabase) {
            using (var qCommand = new SqlCommand(@"SELECT db_id('" + sDatabase + "')", qConnection))
            {
                return (qCommand.ExecuteScalar() != DBNull.Value);
            }
        }
    }
}
 

Output

The database homeschool does not exist.
The database xoax exists.
The database christian does not exist.
The database math does not exist.
The database catholic exists.
Press any key to continue . . .
 

Databases

Databases
 
 

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