是否可以在一个函数中多次连接数据库?
如果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");
}
}
答案 0 :(得分:0)
是的,您可以连接到数据库的次数与可用连接数一样多。你应该能够做你想做的事。
答案 1 :(得分:0)
你可以做任意多次,尽管你也可以重复使用连接。
但您的代码是否是一个好代码?答案是否。您需要正确设计应用程序。将所有数据访问功能移到单独的层中,并在那里完成所有数据库工作。
if (true)
{
using (SqlConnection conn = new SqlConnection("connectionString"))
{
//your code
}
using (SqlConnection conn = new SqlConnection("connectionString"))
{
//your code
}
}
答案 2 :(得分:0)
您的代码中存在很多问题。
首先,是的,您可以多次连接,但是,您可以重复使用相同的连接。你每次都不需要新的连接。
其次,请在命令/连接上调用Dispose,否则会泄漏资源。
第三,将整个表加载到内存中只计算有多少行是个坏主意。而是执行一个计算项目的查询:
Select count(*) from ....