SQL connection to database repeating

Posted by user175084 on Stack Overflow See other posts from Stack Overflow or by user175084
Published on 2010-03-19T17:08:19Z Indexed on 2010/03/19 17:11 UTC
Read the original article Hit count: 239

Filed under:
|
|
|

ok now i am using the SQL database to get the values from different tables... so i make the connection and get the values like this:

        DataTable dt = new DataTable();
        SqlConnection connection = new SqlConnection();
        connection.ConnectionString = ConfigurationManager.ConnectionStrings["XYZConnectionString"].ConnectionString;
        connection.Open();
        SqlCommand sqlCmd = new SqlCommand("SELECT * FROM Machines", connection);
        SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);

        sqlCmd.Parameters.AddWithValue("@node", node);
        sqlDa.Fill(dt);
        connection.Close();

so this is one query on the page and i am calling many other queries on the page.

So do i need to open and close the connection everytime...???

also if not this portion is common in all:

DataTable dt = new DataTable();
        SqlConnection connection = new SqlConnection();
        connection.ConnectionString = ConfigurationManager.ConnectionStrings["XYZConnectionString"].ConnectionString;
        connection.Open();

can i like put it in one function and call it instead.. the code would look cleaner... i tried doing that but i get errors like:

Connection does not exist in the current context.

any suggestions???

thanks

© Stack Overflow or respective owner

Related posts about c#

Related posts about ASP.NET