【问题标题】:Using DbConnection without opening it first使用 DbConnection 而不先打开它
【发布时间】:2016-06-15 08:12:00
【问题描述】:

我正在使用 DbProviderFactories 提供的通用 DbConnection 访问数据库,并且我观察到在使用连接之前我不需要调用 Open。我提供了一个有效的示例代码(使用“System.Data.SqlClient”或“Oracle.DataAccess.Client”作为 providerInvariantName 参数)。我已经使用类似的代码执行了所有 CRUD 操作,而没有在连接上显式调用 Open,没有任何明显的错误。

我知道我不需要关闭它,因为 using 语句负责关闭和处理连接。 但是,什么时候在这段代码中打开连接呢?当我在关联的 DataAdapter 上调用 Fill 时,它会自动打开吗?在使用连接对象之前未在连接对象上显式调用 Open 是否有任何后果? 因为如果它是不必要的,我可以为自己节省几行代码,我肯定会这样做。 ;-)

DbProviderFactory myFactoryProvider = DbProviderFactories.GetFactory("System.Data.SqlClient");// same with "Oracle.DataAccess.Client"
using (var myConnection = myFactoryProvider.CreateConnection())
using (var myCommand = myFactoryProvider.CreateCommand())
{
    try
    {       
        // Set up the connection                  
        myConnection.ConnectionString = _someConnectionString;
        myCommand.Connection = myConnection;
        myCommand.CommandText = "SELECT * FROM SOME_TABLE";     

        // Create DataAdapter and fill DataTable                    
        DbDataAdapter dataAdapter = myFactoryProvider.CreateDataAdapter();
        dataAdapter.SelectCommand = myCommand;
        DataTable myTable = new DataTable();
        dataAdapter.Fill(myTable);
        // Read the table and do something with the data
        foreach (DataRow fila in myTable.Rows)
        {
            // Do  something
        }                          
    }
    catch (Exception e)
    {
        string message = e.ToString();
        throw;
    }
} //using closes and disposes the connection and the command

【问题讨论】:

    标签: c# dbconnection dbproviderfactories


    【解决方案1】:

    语句时应建立并打开与db的连接

    dataAdapter.Fill(myTable);
    

    运行,所以你的代码运行良好

    【讨论】:

    • “应该”是否意味着它是?
    • Fill 方法运行时打开连接。断开连接的 ADO.NET 对象,如 DataAdapter,以这种方式工作:当 Fill 方法运行时,首先打开与数据库的连接,然后另一个断开连接的对象,如 DataTable,用作容器,被填充,然后连接被关闭。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-13
    • 1970-01-01
    • 1970-01-01
    • 2013-09-02
    • 1970-01-01
    • 2017-08-23
    相关资源
    最近更新 更多