使用已打开的数据库连接 [英] work with an already open database connection

查看:152
本文介绍了使用已打开的数据库连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这有点奇怪,但我想检查连接到我的数据库是否已经打开或没有?如何检查?如果打开我想能够直接使用它,而不必通过所有的语句:

This is a little wierd, but I want to check if connection to my database is already open or not? How do I check that? and if open I want to be able to work with it straightaway without going through all the statements:

sqlconnection conn = new sqlconnection("string ...");

这样做可以吗?我知道连接字符串和连接名称。

Can this be done? I know the connection string and the connection name too. I want to check if this connection is available first and then proceed.

推荐答案

如果您知道连接字符串,那么最简单的方法是获取一个新的可用的sql连接是创建SqlConnection类的一个新实例:

If you know the connection string then the easiest way of obtaining a new usable sql connection is to create a new instance of the SqlConnection class:

using (SqlConnection conn = new SqlConnection("MyConnectionString"))
{
    conn.Open();
    // Use the connection
}

.Net框架使用连接池所以没有必要担心打开效率和效率。多个连接 - 上述代码将重新使用可用的现有连接,或根据需要创建一个新的连接。

The .Net framework uses connection pooling and so there is no need to worry about opening efficiency & multiple connections - the above code will either re-use an available existing connection, or create a new one as required.

如果你想保存自己一些键入,发现创建一个小助手方法或属性很有用:

If you want to save yourself some typing then you might find it useful to create yourself a small helper method or property:

class SqlHelper
{
    public static SqlConnection GetConn()
    {
        SqlConnection returnValue = new SqlConnection("MyConnectionString");
        returnValue.Open();
        return returnValue;
    }
}

用法:

using (SqlConnection conn = SqlHelper.GetConn())
{
    // Use the connection
}

这篇关于使用已打开的数据库连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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