How bad is opening and closing a SQL connection for several times? What is the exact effect?

后端 未结 3 1117
独厮守ぢ
独厮守ぢ 2021-01-14 14:51

For example, I need to fill lots of DataTables with SQLDataAdapter\'s Fill() method:

DataAdapter1.Fill(DataTable1);
DataAdapter2.Fill(DataTable2);
DataAdapte         


        
3条回答
  •  半阙折子戏
    2021-01-14 15:34

    ADO.NET has connection pooling, e.g. when you close a connection, it's not really completely closed, but "recycled" if you ask for a new connection with exactly the same connection string.

    Nevertheless - if you already know ahead of time that you'll have to call these five Fill methods one by one, I would definitely recommend

    • opening the connection
    • reading all five data tables from the database
    • closing the connection again right away

    It's accepted best practice to do it this way, it doesn't hurt you - so just do it! :-)

    Marc

    PS: Connection pooling in ADO.NET of course only works if you haven't turned it off ! :-) It's on by default - you'd have to explicitly disable it.

提交回复
热议问题