简体   繁体   中英

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

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 :).

I would guess that your path does not match the location of your Database.mdf file.

Try to debug and see the actual value of your path variable and you may find that Replace didn't work and your path looks someting like bin\\Debug\\MediaPlayer.exeDatabase.mdf .

I would recommend to put the connection string into an app.config instead of finding it via Reflection.


update

It could be that the reason for this problem are insufficient privileges of the account your SQL Server is running under as described in Deploying SQL Express database files with ClickOnce App using OLE .

Try moving your database file to a different location than project debug folder.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM