ps :我试图关闭连接和数据读取器,但它不起作用,也在这里尝试了以前的解决方案,但仍然得到错误 我什至分离了连接,但它效果不佳 我在这里要做的是从SQL服务器从表中读取ID 并使用该 ID 在另一个表中查找其他数据 但它总是给我关闭连接或数据问题
SqlConnection cnx = new SqlConnection("data source = . ; database = tnt ; integrated security = true ; MultipleActiveResultSets=true");
SqlConnection cnx2 = new SqlConnection("data source = . ; database = tnt ; integrated security = true ; MultipleActiveResultSets=true");
SqlCommand cmd = new SqlCommand("select matricule from inscription where numformation = @n",cnx);
cmd.Parameters.AddWithValue("@n", comboBox2.Text);
SqlDataReader dr = cmd.ExecuteReader();
List<string> hawhaw = new List<string>();
while (dr.Read())
{
hawhaw.Add(dr[0].ToString());
}
cmd.Dispose();
cnx2.Close();
cnx2.Open();
SqlCommand cmd2 = new SqlCommand("select * from person where matricule = @m", cnx2);
foreach (var item in hawhaw)
{
cmd2.Parameters.Clear();
cmd2.Parameters.AddWithValue("@m", item);
SqlDataReader dr2 = cmd2.ExecuteReader();
if (dr2.Read())
{
MessageBox.Show(dr2[0].ToString());
}
}
cmd2.Dispose();
cnx.Close();
最重要的是,您可以管理处置和关闭操作。为此,您应该使用using
并将代表您完成这项工作。
List<string> hawhaw = new List<string>();
using (SqlConnection connection = new SqlConnection("data source = . ; database = tnt ; integrated security = true ; MultipleActiveResultSets=true"))
{
connection.Open();
using (SqlCommand cmd = new SqlCommand("select matricule from inscription where numformation = @n", connection))
{
cmd.Parameters.AddWithValue("@n", comboBox2.Text);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
hawhaw.Add(dr[0].ToString());
}
}
}
using (var connection = new SqlConnection("data source = . ; database = tnt ; integrated security = true ; MultipleActiveResultSets=true"))
{
connection.Open();
foreach (var item in hawhaw)
{
using (var cmd2 = new SqlCommand("select * from person where matricule = @m", connection))
{
cmd2.Parameters.AddWithValue("@m", item);
var dr2 = cmd2.ExecuteReader();
if (dr2.Read())
{
MessageBox.Show(dr2[0].ToString());
}
}
}
}