问题描述
我尝试通过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:错误:无法初始化OLE
08:44:17:错误:无法初始化OLE
"08:44:17: Error: Cannot initialize OLE08:44:17: Error: Cannot initialize OLE"
我试图寻找一个解决方案, ve不成功。我也尝试重新启动我的电脑,这也没有帮助。
I've tried looking for a solution, but I've been unsuccessful. I also tried restarting my computer, which didn't help either.
我正在运行SQL Server 2008,这里是相关的数据库代码:
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.
在ExecuteQuery方法的connection.Open()行中调用错误(我知道这是因为我注释掉了其他行)。
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 tested my connection to the database and everything checked out, I just don't understand why I can't connect via code.
推荐答案
通过在Main()方法之前添加[STAThread()]来解决这个问题。 :)
For anyone who might be looking, I eventually solved this by adding a [STAThread()] before the Main() method. :)
这篇关于我得到一个“错误:无法初始化OLE”当我尝试连接到数据库? C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!