1

对 C# 来说相当新,无论如何,我有我编写的这个 Initialise 方法,它基本上创建一个到 MS2007 Access 数据库的连接,用 4 个数据表填充一个数据集,这些数据表是一些查询的结果。

    public frmDBCompareForm()
    {
        ///
        /// Required for Windows Form Design support
        ///
        InitializeComponent();
        frmDBCompareForm_Initialize();

        //
        // TODO: Add any constructor code
        //
        if (_InstancePtr == null) _InstancePtr = this;
    }

以及 Initialise 方法的开始,包括正在填充的 DataTables 之一:

private void frmDBCompareForm_Initialize()
    {
        // Fill DataSet with 3 DataTables, these tables will be 
        // made up of the from sQuery.
        try
        {
            // Create a new DataSet
            DataSet dsSite1 = new DataSet();
            // Set up the connection strings to HCAlias.accdb
            OleDbConnection con = new OleDbConnection();
            con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\HCAlias.accdb;Persist Security Info=False;";
            con.Open();
            //
            // Table 1 - dtSite1Name [cmbSite1]
            //
            dtSite1Name = new DataTable();
            string sQuery = "SELECT SourceName From Sites";
            OleDbCommand cmdSite1Name = new OleDbCommand(sQuery, con);
            OleDbDataAdapter myDASite1Name = new OleDbDataAdapter(cmdSite1Name);
            myDASite1Name.Fill(dsSite1, "dtSite1Name");
            cmbSite1.DataSource = dtSite1Name;
            cmbSite2.DataSource = dtSite1Name;

谁能指出我按照我的方式做这件事的正确方向?有什么提示或建议可以解决该连接问题?我一直像老板一样在谷歌上搜索,但似乎找不到我遇到的确切问题。

4

2 回答 2

3

您还需要关闭您的连接。在您的 finally 块上添加:

        using (var con = new OleDbConnection())
        {
            con.Open();
            using (var cmd = new OleDbCommand("sqlquery", conn))
            {

                try
                {
                             //do Stuff here
                }
                catch (OleDbException)
                {

                    throw;
                }

            }
         }

问候

于 2011-06-27T01:37:28.940 回答
2

此错误是由于保持连接打开而引起的。它不一定会立即发生,但总是在相同数量的请求之后发生。

我建议使用 using 语句包装您的 IDisposable 数据库类:

using (OleDbConnection con = new OleDbConnection())
{

}

这将自动调用 Dispose() 方法的实现并关闭您的连接。

来自 MSDN:“using 语句确保即使在调用对象上的方法时发生异常也会调用 Dispose。您可以通过将对象放在 try 块中,然后在 finally 块中调用 Dispose;在事实上,这就是编译器翻译 using 语句的方式。” ...所以你不需要你的 try catch finally

于 2011-06-27T01:14:56.593 回答