gpt4 book ai didi

c# - 错误告诉我我还没有关闭连接,但不是吗?

转载 作者:太空宇宙 更新时间:2023-11-03 18:41:31 24 4
gpt4 key购买 nike

我一定是漏掉了什么。我正在尝试创建一个表,但我收到一条错误消息,告诉我连接仍处于打开状态。但是哪里???我重新阅读了代码,但找不到连接仍然打开的位置...

问题出在这里: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

他们的 ADOX 对象名为 cat。他们有以下几点:

cat.ActiveConnection = Nothing

这可能会转化为:

createMSFile.ActiveConnection = null

在您的代码中(可能在第一个 Finally block 中)。我认为是 ADOX 对象造成了差异,在处理它之前,尝试将它的 ActiveConnection 设置为 null。

关于c# - 错误告诉我我还没有关闭连接,但不是吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8266300/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com