更新旧软件,但为了保持向后兼容性,我需要连接到.mdb(访问)数据库。
我使用以下连接,但一直有异常,为什么?
我已经验证了路径,数据库存在等等,这一切都是正确的。
string Server = "localhost";
string Database = drive + "\\btc2\\state\\states.mdb";
string Username = "";
string Password = "Lhotse";
string ConnectionString = "Data Source = " + Server + ";" +
"Initial Catalog = " + Database + ";" +
"User Id = '';" +
"Password = " + Password + ";";
SqlConnection SQLConnection = new SqlConnection();
try
{
SQLConnection.ConnectionString = ConnectionString;
SQLConnection.Open();
}
catch (Exception Ex)
{
// Try to close the connection
if (SQLConnection != null)
SQLConnection.Dispose();
//
//can't connect
//
// Stop here
return false;
}
异常消息是:
建立与SQL Server的连接时发生与网络相关或特定于实例的错误。服务器未找到或无法访问。验证实例名称是否正确,以及SQL Server是否配置为允许远程连接。 (提供者:命名管道提供程序,错误:40 - 无法打开与SQL Server的连接)
答案 0 :(得分:4)
究竟是什么让您认为SQL Server连接(SqlConnection)愿意连接到MDB Access数据库?
如果您连接到Access,请使用OleDbConnection。对于Access连接字符串,请参阅http://www.connectionstrings.com/access
答案 1 :(得分:2)
您需要在连接字符串中添加数据提供程序:
Provider = Microsoft.Jet.OLEDB.4.0; Data Source = C:\ mydatabase.mdb; User Id = admin; Password =;
答案 2 :(得分:-1)
使用using
子句尝试这个更安全的版本...对于Database
变量,使用System.IO.Path.Combine
方法会更好更安全......:
string Server = "localhost"; string Database = System.IO.Path.Combine(@"C:\", @"\btc2\state\states.mdb"); string Username = ""; string Password = "Lhotse"; string ConnectionString = "Data Source = " + Server + ";" + "Initial Catalog = " + Database + ";" + "User Id = '';" + "Password = " + Password + ";"; bool bDatabaseOk = false; using (SqlConnection SQLConnection = new SqlConnection()){ try { SQLConnection.ConnectionString = ConnectionString; SQLConnection.Open(); bDatabaseOk = true; } catch (SqlException Ex) { // Handle the SqlException here.... // //can't connect bDatabaseOk = false; } } return bDatabaseOk;