65.9K
CodeProject is changing. Read more.
Home

An Easy Way To Query a Database

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

Feb 14, 2011

CPOL
viewsIcon

6630

The sample code provided by Andrew Rissing is a huge improvement over the original, but incorrectly catches the exception and displays a MessageBox. (Andrew correctly points out this is not a good idea.)A better solution is to allow the exception to fail:public DataSet...

The sample code provided by Andrew Rissing is a huge improvement over the original, but incorrectly catches the exception and displays a MessageBox. (Andrew correctly points out this is not a good idea.) A better solution is to allow the exception to fail:
public DataSet select_query(string query, string con_str)
{
    using (SqlConnection con = new SqlConnection(con_str))
    {
       using (SqlCommand comd = new SqlCommand(query, con))
       {
         using (SqlDataAdapter da = new SqlDataAdapter(comd))
         {
           DataSet ds = new DataSet();
           da.Fill(ds);  // Automatically opens/closes connection.
           return ds;
         }
       }
     }
  }
}
;
public int modify_query(string query, global_data data)
{
    using (SqlConnection con = new SqlConnection(data.Con_Str))
    {
      using (SqlCommand comd = new SqlCommand(query, con))
      {
        con.Open();
        try
        {
          int x = comd.ExecuteNonQuery();
          return x;
        }
        finally
        { 
          con.Close();
        }
      }
    }
  }
}