SQLConnection.Open();引发异常 [英] SQLConnection.Open(); throwing exception

查看:1983
本文介绍了SQLConnection.Open();引发异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更新一块旧的软件,但为了保持向后兼容性,我需要连接到一个.MDB(访问)数据库。



我使用下面的连接但不断收到一个例外,为什么?



我已经验证了路径,数据库等的存在,这是正确的。

 字符串服务器=localhost的; 
串数据库=驱动+\\btc2\\state\\states.mdb
字符串用户名=;
字符串密码=洛子峰;

字符串的ConnectionString =数据源=+服务器+; +
初始目录=+数据库+; +
用户ID =''; +
密码=+密码+;;

的SqlConnection的SQLConnection =新的SqlConnection();


{
SQLConnection.ConnectionString = ConnectionString的;
SQLConnection.Open();
}
赶上(异常前)
{
//尝试关闭连接
如果(的SQLConnection!= NULL)
SQLConnection.Dispose() ;

//
//无法连接
//

//到此为止
返回FALSE;
}



异常消息为:




一个网络相关的或建立到SQL Server的连接发生特定实例的错误。服务器未找到或无法访问。验证实例名称是否正确,以及SQL Server配置为允许远程连接。 (provider:命名管道提供程序,error:40 - 无法打开到SQL Server的连接)



解决方案

是什么让你认为一个SQL Server连接(SqlConnection的)将愿意连接到一个MDB Access数据库???



如果您连接到访问,使用的OleDbConnection 。对于Access连接字符串,请参见 http://www.connectionstrings.com/access


Updating an old piece of software but in order to maintain backward compatibility I need to connect to a .mdb (access) database.

I am using the following connection but keep getting an exception, why?

I have validated the path, database existence etc. and that is all correct.

            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;
            } 

The exception message is:

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)

解决方案

What exactly makes you think that a SQL Server connection (SqlConnection) will be willing to connect to an MDB Access database???

If you connect to Access, use OleDbConnection. For Access connection strings, see http://www.connectionstrings.com/access

这篇关于SQLConnection.Open();引发异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆