0

是否可以在一个函数中多次连接到数据库?

如果SqlCommand不填表。

一段代码:

        public void region_wypelnij()
        {
        string Region = RegionTextBox.Text;
        string Kraj = ((DataRowView)KrajComboBox.SelectedItem).Row.ItemArray[0].ToString();

        String tresc = "Data source=ADAM_LAPTOP; Integrated Security=true; Database=tmargacz";
        SqlConnection conn = new SqlConnection(tresc);
        SqlCommand polecenie = new SqlCommand("Select IdRegionu From Region Where Nazwa='" + Region + "'", conn);
        SqlDataAdapter adapter = new SqlDataAdapter(polecenie);
        DataSet ds = new DataSet(); //reprezentują całą bazę danych wraz z relacjami pomiędzy tabelami
        adapter.Fill(ds, "Region");

        int licznik = ds.Tables["Region"].Rows.Count;
        MessageBox.Show(licznik.ToString());


        if (licznik > 0)
        { 
            string index = ds.Tables["Region"].Rows[0]["IdRegionu"].ToString();
            int indeks = Convert.ToInt32(index);

            String tresc2 = "Data source=ADAM_LAPTOP; Integrated Security=true; Database=tmargacz";
            SqlConnection conn2 = new SqlConnection(tresc2);
            SqlCommand polecenie2 = new SqlCommand("INSERT INTO Region VALUES ((SELECT Nazwa FROM Region WHERE IdRegionu ='" + indeks + "'), (SELECT IdKraju FROM Kraj WHERE Nazwa ='" + Kraj + "'))", conn2);
            SqlDataAdapter adapter2 = new SqlDataAdapter(polecenie2);
            DataSet ds2 = new DataSet(); //reprezentują całą bazę danych wraz z relacjami pomiędzy tabelami
            adapter.Fill(ds2, "Region");
        }
        else
        {
            String tresc2 = "Data source=ADAM_LAPTOP; Integrated Security=true; Database=tmargacz";
            SqlConnection conn2 = new SqlConnection(tresc2);
            SqlCommand polecenie2 = new SqlCommand("INSERT INTO Region VALUES ('" + Region + "', (SELECT IdKraju FROM Kraj WHERE Nazwa ='" + Kraj + "'))", conn2);
            SqlDataAdapter adapter2 = new SqlDataAdapter(polecenie2);
            DataSet ds2 = new DataSet(); //reprezentują całą bazę danych wraz z relacjami pomiędzy tabelami
            adapter.Fill(ds2, "Region");
        }
    }
4

3 回答 3

0

Yes, you can connect to the database as many times as you have available connections. You should be able to do what you are trying to do.

于 2013-08-16T16:54:50.887 回答
0

您可以随意执行多次,但您也可以重复使用连接。

但是你的代码是好代码吗?答案是否定的。您需要正确设计您的应用程序。将所有数据访问功能移到一个单独的层中,并在那里完成所有数据库工作。

if (true)
{
   using (SqlConnection conn = new SqlConnection("connectionString"))
   {
         //your code
   }
   using (SqlConnection conn = new SqlConnection("connectionString"))
   {
        //your code
   }
}
于 2013-08-16T17:00:28.570 回答
0

您的代码中有很多问题。

首先,是的,您可以多次连接,但是,您可以重复使用相同的连接。你真的不需要每次都建立新的连接。

其次,请在您的命令/连接上调用 Dispose,否则您会泄漏资源。

第三,将整个表加载到内存中只是为了计算有多少行是一个坏主意。相反,执行一个计算项目的查询:

 Select count(*) from ....
于 2013-08-16T17:02:05.623 回答