private void button5_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=MAZI-PC\\PROJECTACC;Initial Catalog=programDB;Integrated Security=True");
SqlCommand cmd = new SqlCommand("select label_sh from label_text where label_form='2' and label_form_labelID='1'", conn);
conn.Open();
label1.Text = cmd.ExecuteReader().ToString();
conn.Close();
SqlConnection conn1 = new SqlConnection("Data Source=MAZI-PC\\PROJECTACC;Initial Catalog=programDB;Integrated Security=True");
SqlCommand cmd1 = new SqlCommand("select label_sh from label_text where label_form='2' and label_form_labelID='2'", conn1);
conn1.Open();
label2.Text = cmd1.ExecuteReader().ToString();
conn1.Close();
SqlConnection conn2 = new SqlConnection("Data Source=MAZI-PC\\PROJECTACC;Initial Catalog=programDB;Integrated Security=True");
SqlCommand cmd2 = new SqlCommand("select label_sh from label_text where label_form='2' and label_form_labelID='3'", conn2);
conn2.Open();
label3.Text = cmd2.ExecuteReader().ToString();
conn2.Close();
}
I fetch the label texts from database. But in every fetching operation I open a connection in order to write a query. This is my first project in C#. How can I write a few query without opening many connections ? can anyone help me?
using-statementto ensure that a connecion gets closed even in case of exception. You should always use it when a class implementsIDisposable.Connection-Poolingyou’re not always opening and closing connections when you callcon.Open()orcon.Close(). ActuallyClosejust makes the connection reusable, otherwise it would be marked as “in use”. So it’s good practise to close connections as soon as possible.You could use a
DataAdapterto fill aDataTablewith one query. Then you would have all three records and could take what you need:Note that you need to add
using System.Linq;forLinq-To-DataTable.