Skip to main content
 首页 » 编程设计

c#之帮助减少与数据库的连接数

2024年02月24日24me-sa

我有一个字符串列表,它们只是发票号。 我通过此列表进行枚举以从数据库中获取每张发票的详细信息。 此列表的大小很容易达到 700 到 1000。 我现在这样做的方式导致与数据库的 700-1000 个连接。 这需要很长时间才能完成 有没有更好的方法来做到这一点,我只是不知道?任何指针都会很棒。

这是我的枚举示例

foreach(string i in invoiceList) 
{ 
  Invoice inv = invoiceData.GetInvoice(i); 
  //do something with the invoice 
} 

然后这里是我使用ado.net的数据访问方法的例子

public Invoice GetInvoice(string invoice) 
{ 
      SqlConnection con = new SqlConnection(//connection string); 
      SqlCommand cmd = new SqlCommand("dbo.getInvoices", con); 
      cmd.CommandType = CommandType.StoredProcedure; 
      cmd.Parameters.Add("invoice", SqlDbType.VarChar).Value = invoice; 
      SqlDataReader dr; 
      Invoice inv = new Invoice(); 
      try{ 
            con.Open(); 
            dr = cmd.ExecuteReader 
            while(dr.read()) 
            { 
                 //assign values from the database fields 
            } 
 
 
      } 
      catch{} 
      finally{con.close();} 
 
} 

所以基本上 getInvoice 方法被调用 1000 次,每次都打开一个新连接。什么是更好(更快)的方法来做到这一点。 谢谢!

请您参考如下方法:

只需将所有发票编号放入 IN 语句中,然后在单个连接中运行此选择语句。