I get an “Error: Cannot initialize OLE” when I try to connect to a database? C#

大憨熊 提交于 2019-12-12 20:34:20

问题


I'm trying to connect to a database via C#, but I'm getting a very unhelpful error message when I do so:

"08:44:17: Error: Cannot initialize OLE 08:44:17: Error: Cannot initialize OLE"

I've tried looking for a solution, but I've been unsuccessful. I also tried restarting my computer, which didn't help either.

I am running SQL Server 2008, and here is the relevant database code:

/// <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();
    }

This is database code that I have used for several project, and it has always worked before.

The error is called (I know this because I commented out other lines) on the connection.Open() line in the ExecuteQuery method.

Any help/advice would be greatly appreciated :).

EDIT: I tested my connection to the database and everything checked out, I just don't understand why I can't connect via code.


回答1:


For anyone who might be looking, I eventually solved this by adding a [STAThread()] before the Main() method. :)




回答2:


I suspect that you are building the project for x64 CPU. There is no OLE driver for x64. I recommend to change the build target from ANY CPU to x86.



来源:https://stackoverflow.com/questions/10561405/i-get-an-error-cannot-initialize-ole-when-i-try-to-connect-to-a-database-c-s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!