数据库连接 [英] DB Connection

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

问题描述



请帮帮我...

我对数据库连接有疑问.我在类文件中调用了DB,现在我想在我的应用程序中的每个应用程序中使用此连接.如何在Class File中调用DB连接给其他人并使用它.

您可以用代码解释吗?



Please help me...

I have doubt regarding DB connection. I have called DB in class file and now i want to use this connection in every were in my application. how to call DB connection in Class File to others and use it.

Can you explain with code please?

推荐答案

在应用程序的整个生命周期中保持开放状态不是一个好主意.虽然,您可能有一个为您完成连接的打开和关闭的类,所以您不必一次又一次地编写相同的代码.这是我可以建议的:

It is not a good idea to leave the connection open through the lifetime of your application. Although, you may have a class which does the opening and closing of the connection for you so that you do not have to write same code again and again. This is something I could suggest:

class DatabaseHelper:IDisposable
    {
        IDbConnection _connection = null;
        public IDbConnection CreateConnection()
        {
            if (_connection == null)
            {
                // create and open the connection here
            }
            else if (_connection.State != ConnectionState.Open)
            {
                _connection.Open();
            }
            return _connection;
        }
        public void Dispose()
        {
            if (_connection != null)
            {
                // Dispose method of some providers do not close the connection even when it is disposed
                _connection.Close();
                _connection.Dispose();
            }
        }
    }



这只是一个示例,根据您所拥有的应用程序类型的不同,可能会在各个级别上失败.



This is just a sample and may fail at various levels depending upon the type of application you have.


我认为您真正想做的是创建一个静态数据库连接类,该类将使您所有类背后的代码可以访问.
例如:((请注意,我只是在未经测试的情况下将这段代码敲入了这里,因此可能会出现输入错误和错误,但是我认为它可以为您提供想法.它也不完整,因为您将需要处理它,诸如此类).在某个时候.
I think what you really want to do is create a static db connection class that that all your code behind classes have access to.
For example: (Please note that I just hammered this code into here without testing it, so there are likely typos and errors, but I think it gives you the idea. It is also incomplete in that you will want to handle disposing it and such at some point.
sealed class DatabaseConnectivity
{
    private static SqlConnection _dbConn = null;

    public static SqlConnection GetConnection()
    {
        if( _dbConn == null )
            _dbConn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\Guru\HRP\App_Data\hrp.mdf;Integrated Security=True;User Instance=True"); 

        if( _dbConn.State == ConnectionState.Closed )
            _dbConn.Open();
    }

    return _dbConn;
}



一旦有了这样的类,那么您所要做的就是从使用它的任何表单中调用它.



Once you have a class like this, then all you have to do is call it from whichever form uses it.


如果您使用的是win表单,请参见
If you are using win forms, see here[^].


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

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