错误告诉我我没有关闭连接,但是不是吗? [英] Error tells me I haven't close the connection, but haven't I?
问题描述
我一定在这里错过了一些东西.我正在尝试创建表,但收到一条错误消息,告诉我连接仍处于打开状态.但是哪里???我已经重新阅读了代码,但是找不到连接仍然打开的地方...
I must have missed something here. I am trying to create a table but I am getting an error telling me that connection is still open. But where??? I have re-read the code but I can't find where the connection is still open...
问题出现在这里:objOleDbConnection.Open()
错误提示:
You attempted to open a database that is already opened by user 'Admin' on machine 'machine'. Try again when the database is available.
private void sfdNewFile_FileOk(object sender, System.ComponentModel.CancelEventArgs e)
{
// Creating a ADOX object needed to create
// new MS Access file.
ADOX.Catalog createMSFile = new ADOX.Catalog();
// Creating an object for a table.
Table nTable = new Table();
// Creating an object allowing me connecting to the database.
OleDbConnection objOleDbConnection = new OleDbConnection();
objOleDbConnection.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" +
"Data Source=" + sfdNewFile.FileName + ";Persist Security Info=False;Mode=12";
// Creating command object.
OleDbCommand objOleDbCommand = new OleDbCommand();
objOleDbCommand.Connection = objOleDbConnection;
try
{
// Created a new MS Access 2007 file with specified path.
createMSFile.Create("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
sfdNewFile.FileName);
objOleDbConnection.Open();
objOleDbCommand.CommandText = "CREATE TABLE PersonalData (" +
"[DataID] AUTOINCREMENT NOT NULL PRIMARY KEY ," +
"[Type] VARCHAR(40) NOT NULL ," +
"[URL] VARCHAR(40) NOT NULL ," +
"[SoftwareName] VARCHAR(40) NOT NULL ," +
"[SerialCode] VARCHAR(40) NOT NULL ," +
"[UserName] VARCHAR(40) NOT NULL ," +
"[Password] VARCHAR(40) NOT NULL";
objOleDbCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
// Displaying any errors that
// might have occured.
MessageBox.Show("Error: " + ex.Message);
}
finally
{
// It is importnat to release COM object, in this very order
// otherwise we eill end up with an error.
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(createMSFile);
// Closing the connection to the database.
objOleDbConnection.Close();
}
}
推荐答案
似乎ADOX对象也应该关闭其连接. 查看来自Microsoft的以下示例: http://msdn.microsoft. com/en-us/library/windows/desktop/ms681562(v = vs.85).aspx
It seems that the ADOX object should close its connection as well. Look at the following sample from Microsoft: http://msdn.microsoft.com/en-us/library/windows/desktop/ms681562(v=vs.85).aspx
他们的ADOX对象被命名为cat. 它们具有以下内容:
Their ADOX object is named cat. They have the following:
cat.ActiveConnection = Nothing
这可能会翻译为:
createMSFile.ActiveConnection = null
在您的代码中(可能在第一个Final代码块中). 我认为是ADOX对象有所作为,在分配它之前,尝试将其ActiveConnection设置为null.
In your code (probably in the first Finally block). I think it's the ADOX object that makes the difference, before dispoing it, try to set it's ActiveConnection to null.
这篇关于错误告诉我我没有关闭连接,但是不是吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!