SQL连接无法正常工作错误:26 - 找到指定的服务器/实例时出错

时间:2014-05-21 13:20:08

标签: c# sql error-handling

我有两个连接到数据库第一个工作的例子,第二个没有。

错误说:

类型' System.Data.SqlClient.SqlException'的未处理异常发生在SQL backup.exe中 附加信息:建立与SQL Server的连接时发生与网络相关或特定于实例的错误。服务器未找到或无法访问。验证实例名称是否正确,以及SQL Server是否配置为允许远程连接。 (提供程序:SQL网络接口,错误:26 - 查找指定的服务器/实例时出错)

.sdf文件的位置在两个类中都是相同的我使用相同的路径,如何配置第一类工作适当?

  string conn = @"Data Source = C:\Users\admin\Documents\visual studio 2013\Projects\SQL backup\SQL backup\sdf\locals.sdf";
    // want work
    public Connections()
    {
        try
        {
            SqlConnection con = new SqlConnection(conn);
            con.Open();
            try
            {
                SqlCommand com = new SqlCommand("select * from tblUsers", con);
                SqlDataReader reader = com.ExecuteReader();
                while (reader.Read())
                {
                    MessageBox.Show(reader.GetString(0));
                }
            }
            catch (SqlException ex)
            {
                MessageBox.Show(ex.Message); throw;
            }
        }
        catch (SqlException ex)
        {
            MessageBox.Show(ex.Message);
            throw;
        }

    }
    // working
    string localsdf = @"Data Source = C:\Users\admin\Documents\visual studio 2013\Projects\SQL backup\SQL backup\sdf\locals.sdf";
    public ConnectionCe()
    {
        try
        {
            SqlCeConnection sqlcon = new SqlCeConnection(localsdf);
            sqlcon.Open();

            SqlCeCommand com = new SqlCeCommand("select * from tblUsers", sqlcon);

            using (SqlCeDataReader reader = com.ExecuteReader())
            {
                infolist = new List<information>();
                while (reader.Read())
                {
                    info = new information();
                    info.username = reader.GetString(0);
                    info.age = reader.GetInt32(1);
                    infolist.Add(info);
                }
            }
            sqlcon.Close();
        }
        catch (SqlCeException ex)
        {
            MessageBox.Show(ex.Message);
            throw;
        }

0 个答案:

没有答案