(C#WPF SQL Server)是否可以在一个函数中多次连接到数据库



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

如果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");
        }
    }

您可以随心所欲地进行多次操作,但也可以重用连接。

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

if (true)
{
   using (SqlConnection conn = new SqlConnection("connectionString"))
   {
         //your code
   }
   using (SqlConnection conn = new SqlConnection("connectionString"))
   {
        //your code
   }
}

是的,只要有可用的连接,就可以多次连接到数据库。你应该能够做你想做的事情。

您的代码中有很多问题。

首先,是的,您可以多次连接,但是,您可以重用相同的连接。你并不真的每次都需要一个新的连接。

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

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

 Select count(*) from ....

最新更新