Check if SQL Database Exists with C#

Good Morning! I wanted to give a shout out to another blogger who linked to us yesterday here. It was so nice of him you know? Just amazing, the generosity of some folks out there!

Today’s code was a rewrite of the vb.net code here but using C#. One thing of note is that the Using keyword has a completely different meaning in C# so thus has been removed. It wasn’t really needed anyway.

Anyway, so make it a great day!

public Boolean testDatabaseExists(string server, string database)
        {
            String connString = (“Data Source=” + (server + “;Initial Catalog=master;Integrated Security=True;”));
            String cmdText = (“select * from master.dbo.sysdatabases where name=\'” + (database + “\'”));
            Boolean bRet;

            System.Data.SqlClient.SqlConnection sqlConnection = new System.Data.SqlClient.SqlConnection(connString);
            System.Data.SqlClient.SqlCommand sqlCmd = new System.Data.SqlClient.SqlCommand(cmdText, sqlConnection);
           
            try
            {
            sqlConnection.Open();
            System.Data.SqlClient.SqlDataReader reader = sqlCmd.ExecuteReader();
            bRet = reader.HasRows;
            sqlConnection.Close();
            }
            catch (Exception e)
            {
            bRet = false;
            sqlConnection.Close();
            MessageBox.Show(e.Message);
            return false;
            } //End Try Catch Block
                      
           
            if (bRet == true)
            {
                MessageBox.Show(“DATABASE EXISTS”);
                return true;
            }
            else
            {
                MessageBox.Show(“DATABASE DOES NOT EXIST”);
                return false;
            } //END OF IF

           
        } //END FUNCTION

Facebook

Advertisements

, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

  1. #1 by Anaya Upadhyay on April 3, 2012 - 2:02 am

    Thanks, It helped me a lot

  2. #2 by HK on July 19, 2013 - 12:30 pm

    Among all those code snippets, this one is the only one that works! (of course I maybe missing some points on the other one cuz Im a SQL noob!!! :D)

  1. [RESOLVED]How to use single save button to insert in 2 tables | ASP Questions & Answers
  2. [RESOLVED]How to use single save button to insert in 2 tables | ASP Web Form Data Control
  3. [RESOLVED]How to use single save button to insert in 2 tables | ASP.NET MVC

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: