每个查询都有一个新的sql连接? [英] A new sql connection for each query?

查看:95
本文介绍了每个查询都有一个新的sql连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个与本地sql服务器通信的服务器应用程序。

I'm writing a server application that's communication with a local sql server.

每个客户端都需要读取或写入数据到数据库。

Each client will need to read or write data to the database.

最好有一个线程安全类,它将在单个sql连接上入队和执行sql命令?或者我应该为每个命令打开一个新的连接?

Would it be better to have a thread safe class which will enqueue and executes the sql commands on a single sql connection? Or should I open a new connection for each command? Does it matter much for performance?

推荐答案

如果你有一批语句必须彼此执行,你应该使用相同的SqlConnection。
一旦你不再需要SqlConnection,并且你不知道什么时候你需要一个连接,你应该关闭连接。

If you have a batch of statements that have to be executed after each other, you should use the same SqlConnection. As soon as you do not longer need the SqlConnection, and you do not know when you will need a connection again, you should close the connection.

,如果你必须执行2个插入语句和一个更新语句,例如,你应该使用相同的SqlConnection。

这里最重要的优势是,你可以把这些语句放在一个事务如果需要。

So, if you have to execute 2 insert statements and one update statement after each other, for instance, you should use the same SqlConnection.
The most important advantage here, is that you can put those statement in a transaction if necessary. Transactions cannot be shared accross connections.

使用数据库后,您可以关闭连接。默认情况下,使用连接池,并且连接将返回到池,以便在下次需要连接到数据库时可以重新使用。
连接生命周期应该很短,但不应该为每个DbCommand使用单独的连接。

When you're finished working with the DB, you can close the connection. By default, connection pooling is used, and the connection will be returned to the pool, so that it can be reused the next time you need a connection to the DB. Connection lifetime should be short, but you should not use a separate connection for each DbCommand.

这篇关于每个查询都有一个新的sql连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆