+ Reply to Thread
Results 1 to 2 of 2

Thread: C#-SQL issue

  1. #1
    Junior Member
    Join Date
    Jan 2012
    Posts
    34

    C#-SQL issue

    Hello , i am using the below C# code to connect to a database and check if it exist or not .
    Code:
    SqlConnection tmpConn = new SqlConnection("Data Source=localhost\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True");
    
    sqlCheckDBQuery = "SELECT * FROM master.sys.databases where name = \'aspnetdb\'";
    
    using (tmpConn)
    {
        try
        {
            tmpConn.Open();
            tmpConn.ChangeDatabase("master");
        }
        catch (Exception)
        {
            MessageBox.Show("SQLServer Express Database is either not installed or not running!", "Database Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            Application.Exit();
        }
    
        using (SqlCommand sqlCmd = new SqlCommand(sqlCheckDBQuery, tmpConn))
        {
            int exists = sqlCmd.ExecuteNonQuery();
    
            if (exists <= 0)
                databaseExists = false;
            else
                databaseExists = true;
        }
    }
    But once i run it , the ExecuteNonQuery always returns -1 .
    I've seen the master.sys.databases view and it has the database POS

  2. #2
    Junior Member
    Join Date
    Jan 2012
    Posts
    19
    You should use ExecuteScalar() and change the query to run a COUNT(*).
    ExecuteScalar will bring back the rows affected.
    ExecuteNonQuery() will bring back -1 for SELECT's.
    So the query should be be :
    Code:
    sqlCheckDBQuery = "SELECT count(1) FROM master.sys.databases where name = 'aspnetdb'";
    var count = (int)sqlCmd.ExecuteScalar();
    databaseExists = count > 1;

+ Reply to Thread

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts