Click here to Skip to main content
13,297,547 members (44,136 online)
Click here to Skip to main content
Add your own
alternative version

Stats

3.3K views
3 bookmarked
Posted 14 Feb 2011

An Easy Way To Query a Database

, 14 Feb 2011
Rate this:
Please Sign up or sign in to vote.
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();
        }
      }
    }
  }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

woric
Web Developer
Australia Australia
This member doesn't quite have enough reputation to be able to display their biography and homepage.

You may also be interested in...

Pro

Comments and Discussions

 
Generalthanx sir for improving Pin
Abdur Rehman Raza Khan - dontumindit14-Feb-11 19:37
memberAbdur Rehman Raza Khan - dontumindit14-Feb-11 19:37 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.171207.1 | Last Updated 14 Feb 2011
Article Copyright 2011 by woric
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid