使用已经打开的数据库连接

发布于 2024-09-29 03:10:15 字数 194 浏览 0 评论 0原文

这有点奇怪,但我想检查与数据库的连接是否已经打开?我该如何检查?如果打开,我希望能够立即使用它,而无需查看所有声明:

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

可以这样做吗?我也知道连接字符串和连接名称。我想先检查此连接是否可用,然后继续。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

吃→可爱长大的 2024-10-06 03:10:15

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

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

.Net框架使用连接池,因此无需担心打开效率和连接问题。多个连接 - 上面的代码将重新使用可用的现有连接,或根据需要创建一个新连接。

如果您想节省一些打字时间,那么您可能会发现为自己创建一个小辅助方法或属性很有用:

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

用法:

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

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
}

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;
    }
}

Usage:

using (SqlConnection conn = SqlHelper.GetConn())
{
    // Use the connection
}
泪意 2024-10-06 03:10:15

您看过 SqlConnection 的文档吗?

http://msdn.microsoft.com/en-us /library/system.data.sqlclient.sqlconnection.aspx

我相信“State”属性会告诉您您想要什么。

如果您更一般地询问如何使用连接池中的现有连接,那么当您使用与活动连接相同的连接字符串创建新的 SqlConnection 时,这将自动完成。

如果您只是想避免编写冗余代码,请将其放入类中并重用它。

Have you looked at the documentation for SqlConnection?

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.aspx

I believe the "State" property will tell you what you want.

If you are rather asking more generally how you can use an existing connection from a connection pool, this will be done automatically when you create a new SqlConnection with an identical connection string as an active connection.

If you're just trying to avoid writing redundant code, then put it in a class and reuse it.

雨巷深深 2024-10-06 03:10:15

尽管您可能只使用 SQL Server,但熟悉 System.Data 中的所有核心接口可能是一个好习惯,因为所有数据提供程序都实现了它们。我相信 IDbConnection 上的 State 属性返回您所要求的信息(IDbConnection)

另外,您可能想以某种集中方法隐藏该逻辑:

public static IDbConnection RetrieveConnection(){
    if(DataAccess.Connection.State == ConnectionState.Open) return DataAccess.Connection;

    conn.Dispose(); //to be clean, I believe this is safe if it's already disposed
    //retrieve configured connection string
    //create and open connection
    return DataAccess.Connection;
}

所以也许 DataAccess 是您可以的地方放置和检索您的连接对象,但我会避免让每个人直接使用它。相反,让他们执行此方法可以确保连接可用。我只是想给你一些想法。

另外,您可能想更进一步,使用 NHibernate 之类的东西来为您管理连接和所有这些东西。尽管如果项目很小,这并不总是值得付出努力。

编辑:使代码更明确一点

Although you are probably just using SQL Server it might be good practice to get familiar with all the core interfaces in System.Data since all data providers implement them. I believe the State property on IDbConnection returns the information you are asking for (IDbConnection)

Also you may want to hide that logic in some kind of centralized method:

public static IDbConnection RetrieveConnection(){
    if(DataAccess.Connection.State == ConnectionState.Open) return DataAccess.Connection;

    conn.Dispose(); //to be clean, I believe this is safe if it's already disposed
    //retrieve configured connection string
    //create and open connection
    return DataAccess.Connection;
}

So maybe DataAccess is some place you can put and retrieve your connection object, but I would avoid having everyone use it directly. Instead have them go through this method that can ensure the connection is usable. I'm just trying to give you ideas.

Also you may want to take it a step further and use something like NHibernate that will manage connections and all that stuff for you. Although that's not always worth the effort if the project is small.

EDIT: made the code a little more explicit

谁对谁错谁最难过 2024-10-06 03:10:15

Façade 设计模式应该可以帮助您。这是一个例子。

  1. 外观模式(维基百科)
  2. 外观设计模式(四人组)

“智能”外观知道什么方法需要连接到哪里,等等。外观打开连接并将其传递给底层代码段,通常包含在工厂类或类似的东西中。

public class DoSomethingFacade {
    private static readonly DoSomethingFactory _doSomethingFactory = new DoSomethingFactory();

    public static IList<T> GetList<T>() {
        using(IDbConnection connection = OpenConnection("string..."))
            return _doSomethingFactory.GetList<T>(connection);
    }

    public static IDbConnection OpenConnection(string connectionString) {
        IDbConnection openedConnection = new SqlConnection(connectionString);
        openedConnection.Open();
        return openedConnection;
    }
}

internal class DoSomethingFactory {
    internal DoSomethingFactory() { }

    internal IList<T> GetList<T>(IDbConnection connection) {
        IList<T> results = new List<T>();

        // use connection here without caring about it, 
        // as it should be provided as an opened available connection.

        return results;
    }
}

The Façade Design Pattern should help you here. Here's an example.

  1. Façade Pattern (wikipedia);
  2. Façade Design Pattern (Gang of Four).

An "intelligent" façade knows what method needs to connect where, etc. The façade opens the connection and pass it to an underlying piece of code, generally contained in a factory class or something alike.

public class DoSomethingFacade {
    private static readonly DoSomethingFactory _doSomethingFactory = new DoSomethingFactory();

    public static IList<T> GetList<T>() {
        using(IDbConnection connection = OpenConnection("string..."))
            return _doSomethingFactory.GetList<T>(connection);
    }

    public static IDbConnection OpenConnection(string connectionString) {
        IDbConnection openedConnection = new SqlConnection(connectionString);
        openedConnection.Open();
        return openedConnection;
    }
}

internal class DoSomethingFactory {
    internal DoSomethingFactory() { }

    internal IList<T> GetList<T>(IDbConnection connection) {
        IList<T> results = new List<T>();

        // use connection here without caring about it, 
        // as it should be provided as an opened available connection.

        return results;
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文