How to Check for a database on SQL Server using C#

This is just another SQL C# articles which let you learn how to check for a database existence on SQL Server.

All you have to do query names in sys.databases table and make sure it is available to use. You can create a function for the purpose.

public static bool IsDBExist(string server, string db)
            List<string> list = new List<string>();

            // Open connection to the database
            string conString = null; ;
                conString = "server=" + server + ";uid=sa;";
            bool has = false;
                using (SqlConnection con = new SqlConnection(conString))
                    if (con.State == ConnectionState.Open) con.Close();

                    // Set up a command with the given query and associate
                    // this with the current connection.
                    using (SqlCommand cmd = new SqlCommand("SELECT name from sys.databases where name='" + db + "'", con))
                        using (IDataReader dr = cmd.ExecuteReader())

                            while (dr.Read())
                            if (list.Count > 0) has = true;
            catch (Exception er)
            return has;


Published by


A developer,teacher and a blogger obsessed with Python,Dart and open source world from India

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.