Multiple SQL queries asp.net c#

后端 未结 5 1891
忘掉有多难
忘掉有多难 2020-12-31 18:08

I need to run several queries inside one function, will I have to create a new SqlConnection for each? Or having one connection but different SqlCommands works too?

5条回答
  •  北海茫月
    2020-12-31 18:53

    It doesn't matter which way you go.

    SqlConnections are pooled by the operating system. You could literally open and close a connection thousands of times in a row and not incur any performance or other penalty.

    How it works is:

    1. Application makes a request to create a db connection (var c = new SqlConnection(...))
    2. The Operating Systems connection pool looks to see if it has a connection sitting idle. If it does, you get a reference to that. If not then it spins up a new one.
    3. Application indicates it is finished with the connection (c.Dispose())
    4. Operating System keeps the connection open for a certain amount of time in case your app, or another one, tries to create another connection to that same resource.
    5. If that connection stays idle until a timeout period passes then the OS finally closes and releases.

    This is why the first time you make a connection to a database it might take a second to start before the command(s) can be processed. However if you close it and reopen it then the connection is available immediately. More information is here: http://msdn.microsoft.com/en-us/library/8xx3tyca(v=vs.110).aspx

    Now, as to your code, generally speaking you open 1 SqlConnection each time you make a SqlCommand call; however, it is perfectly acceptable/reasonable to make multiple SqlCommand calls while within the same block under the SqlConnection using clause.

    Just bear in mind that you do NOT want to keep a SqlConnection object hanging around in your code for any longer than is absolutely necessary. This can lead to a lot of potential issues, especially if you are doing web development. Which means it's far better for your code to open and close 100 SqlConnection objects in rapid succession than it is to hold onto that object and pass it around through various methods.

提交回复
热议问题