Is it better to reuse SqlCommand when executing the same SQL query several times?

后端 未结 2 1395
南旧
南旧 2021-01-04 06:44

When querying the database with the same query but different parameters, is it better to:

  • do it in a single using,
  • or to create two separate queries?<
2条回答
  •  一生所求
    2021-01-04 07:12

    There's very little benefit to reusing the command instance, unless you're planning to call Prepare.

    If you're going to run the command many times (dozens or more), then you probably want to create the command, prepare it, execute it in a loop, and then dispose it. The performance gains are significant if you're running the command many times. (You would add the parameters once, though, before you prepare -- not delete and re-add them every time like you're doing in your first code sample. You should change the parameters' values each time, not create new parameters.)

    If you're only going to be running the command a handful of times, performance isn't an issue, and you should go with whichever style you prefer. Creating the command each time has the benefit that it's easy to extract into a method so you don't repeat yourself.

提交回复
热议问题