当我试图连接数据库时,出现“错误:无法初始化OLE”的提示?C#

3
我正在尝试通过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();
    }

这是我在几个项目中使用的数据库代码,以前一直都可以正常工作。

错误发生在ExecuteQuery方法中的connection.Open()行(我知道这一点是因为我注释掉了其他行)。

非常感谢任何帮助和建议 :)

编辑:我测试了与数据库的连接,一切都没问题,我只是不明白为什么不能通过代码进行连接。


首先,打开SSMS并尝试连接到sqlexpress。 - RoMEoMusTDiE
我该如何打开SSMS?抱歉,我经验不足 :P.. 它既不像一个程序,也不像Visual Studio中的工具栏.. - Daniel
SSMS是随SQL Server一起提供的用户界面。因此,您可以打开Microsoft SQL Management Studio,连接到您的服务器并查看SQL Server是否正常工作。 - YvesR
@Daniel,为什么你要这样连接,而不是直接连接到 SQL Server? - YvesR
2个回答

2

如果有人在寻找解决方法,我最终通过在Main()方法之前添加[STAThread()]来解决了这个问题。 :)


0

我怀疑您正在为x64 CPU构建项目。x64没有OLE驱动程序。我建议将构建目标从ANY CPU更改为x86。


也许我误解了,但我打开了项目属性并打开了“生成”面板,在平台下选择的选项是“Active (x86)”。实际上,这是唯一的选项。 - Daniel
我正在运行64位的Windows 7。 - Daniel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接