The following samples should take advantage of
using
statements and furthermore built in features of the ADO.NET framework. Furthermore, if you open a connection, make sure you open it at the latest time possible and close it as soon as possible.
Edit: While I was originally not trying to change too much of the original content, I might as well to incorporate all of the suggestions posted below. As woric and I noticed, the exception handling is generally not a good idea, so it can be removed and handled at a higher level. Though, the using
statement should be used to close the connection, so the try/finally isn't necessary. Then, as Fzelle pointed out, the SqlDataAdapter can be passed the connection string and query to simplify that method.
public DataSet select_query(string query, string con_str)
{
using (SqlDataAdapter da = new SqlDataAdapter(query, con_str))
{
DataSet ds = new DataSet();
da.Fill(ds);
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();
int x = comd.ExecuteNonQuery();
con.Close();
return x;
}
}
}