我正在尝试通过 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() 行上调用的(我知道这一点是因为我注释掉了其他行)。
任何帮助/建议将不胜感激:)。
编辑:我测试了与数据库的连接并检查了所有内容,我只是不明白为什么无法通过代码连接。
对于任何可能正在寻找的人,我最终通过在 Main() 方法之前添加 [STAThread()] 解决了这个问题。 :)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)