Click here to Skip to main content
15,887,821 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello, i am begineer software developer and i want collect information about programming that's why i have a question that why we use connection.open and connection.close in c# on every single query of database i want to know about that please give me the answer with the logical answer so may be i will understannd better

What I have tried:

C#
connection.Open();
            DataSet dsa = new DataSet();
            DataTable dt = new DataTable();
            dsa.Tables.Add(dt);
            OleDbDataAdapter da = new OleDbDataAdapter();
            da = new OleDbDataAdapter("SELECT [User Name] FROM Login where [User Code] = " + comboBox1.Text + " ", connection);
            da.Fill(dt);
            //dataGridView1.DataSource = dt;
            textBox1.Text = dt.Rows[0][0].ToString();
            connection.Close();
Posted
Updated 7-Dec-16 13:17pm
v2
Comments
PIEBALDconsult 7-Dec-16 18:59pm    
A DataAdapter will Open and Close the Connection for you automatically. But please don't use DataAdapters; they suck.
PIEBALDconsult 7-Dec-16 19:17pm    
0) Please learn to use parameters -- never use string concatenation to provide values.
1) If you want only one value from the database; please look into ExecuteScalar.

1 solution

This has nothing to do with C#, but with cost. SQL servers are very expensive beasts and connection licenses were finite and well as other resources on the server. It's your job as a programmer to limit your use of licenses and server resources. So you do that by opening a connection as late as possible, executing your query as quickly and efficiently as possible, and closing the connection as early as possible, freeing up the resources you used for some other query.

This applies in all languages, not just C#.
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900