尝试连接到数据库时收到“错误:无法初始化 OLE”?C#.

本文关键字:初始化 OLE 错误 连接 数据库 | 更新日期: 2023-09-27 18:33:53

我正在尝试通过 C# 连接到数据库,但当我这样做时,我收到一条非常无用的错误消息:

08:44:17:错误:无法初始化 OLE 08:44:17:错误:无法初始化 OLE

我尝试寻找解决方案,但没有成功。我还尝试重新启动计算机,但也没有帮助。

我正在运行SQL Server 2008,以下是相关的数据库代码:

/// <summary>
/// Connects to a given database and returns the database connection.
/// </summary>
/// <param name="file">The database file name.</param>
/// <returns>The database connection.</returns>
public static SqlConnection ConnectToDb(string file)
{
    //initialize generic path
    string path = System.Reflection.Assembly.GetExecutingAssembly().Location;
    path = path.Replace("bin''Debug''MediaPlayer.exe", "");
    path += "Database.mdf";
    string connectionPath = @"Data Source=.'SQLEXPRESS;AttachDbFilename=" + path + ";Integrated Security=True;User Instance=True";
    SqlConnection connection = new SqlConnection(connectionPath);
    return connection;
}
/// <summary>
/// Executes a SQL query in a given database.
/// </summary>
/// <param name="file">The database file name.</param>
/// <param name="query">The SQL query to execute.</param>
public static void ExecuteQuery(string file, string query)
{
    SqlConnection connection = ConnectToDb(file);
    connection.Open();
    SqlCommand command = new SqlCommand(query, connection);
    command.ExecuteNonQuery();
    connection.Close();
}

这是我用于多个项目的数据库代码,它以前一直有效。

在连接上调用错误(我知道这一点,因为我注释掉了其他行)。Open() 行在 ExecuteQuery 方法中。

任何帮助/建议将不胜感激:)。

尝试连接到数据库时收到“错误:无法初始化 OLE”?C#.

我猜你的路径与你的数据库.mdf文件的位置不匹配。

尝试调试并查看path变量的实际值,您可能会发现Replace不起作用,并且您的path看起来像 bin''Debug''MediaPlayer.exeDatabase.mdf

我建议将连接字符串放入 app.config 中,而不是通过反射找到它。


更新

此问题的原因可能是运行 SQL Server 的帐户的权限不足,如使用 OLE 使用 ClickOnce 应用部署 SQL Express 数据库文件中所述。

尝试将数据库文件移动到项目调试文件夹以外的其他位置。