+ -
当前位置:首页 → 问答吧 → 数据库连接错误——在建立与服务器的连接时出错

数据库连接错误——在建立与服务器的连接时出错

时间:2011-12-11

来源:互联网

练习使用一个在线考试的小系统,VS2008已经和SQL2005数据库成功连接了,并且不止一个网页用到了数据库的交互,也没什么问题,例如可以实现添加学生并显示,添加考试课程并显示,学生提交试卷并显示等都能实现,但是涉及到老师从数据库中提取出已经添加的题目组合成一套试题时,出现了这个数据库连接的错误:
“在建立与服务器的连接时出错。在连接到 SQL Server 2005 时,在默认的设置下 SQL Server 不允许进行远程连接可能会导致此失败。 (provider: 命名管道提供程序, error: 40 - 无法打开到 SQL Server 的连接)”
我已经按照网上搜索到的常用解决方法进行了数据库的一些设置,但是这个问题还是会出现,下面是涉及到的代码:
C# code

    protected void CheckPagerName_Click(object sender, EventArgs e)
    {
        AjaxCommond ac = new AjaxCommond();
        SqlDataReader read = [color=#0000FF]ExceRead[/color]("select * from Papermr where PaperName='" + this.txtPaperName.Text +"'");
        read.Read();
        if (read.HasRows)
        {
            if (this.txtPaperName.Text == read["PaperName"].ToString())
            {
                //弹出AJAX环境中的对话框
                ac.OpenDialogForButton((Button)sender, "很遗憾!该试卷名称已经存在!!!");
            }
        }
        else
        {
            //弹出AJAX环境中的对话框
            ac.OpenDialogForButton((Button)sender, "恭喜您!该试卷名称可以添加!!!");
        }
        read.Close();
    }

C# code
 
       public SqlDataReader [color=#0000FF]ExceRead[/color](string strsql)
       {
        [color=#008000]string connStr = "Data Source=(localhost);DataBase=OnLineExam;User ID=sa;Password=123456;";[/color]
        SqlConnection con = new SqlConnection(connStr);
        [color=#0000FF]con.Open();[/color]
        //创建一个SqlCommand对象,表示要执行的SqlCom语句或存储过程
        SqlCommand sqlcom = new SqlCommand(strsql, con);
        SqlDataReader read = sqlcom.ExecuteReader();
        return read;
    }

在上面标注蓝色的代码中即显示了上面所提出的数据库的连接错误,本人已经参照网上的方法对SQL Server配置管理器和SQL Server外围应用配置器做了相应的设置了,但是还是不行。。。。
Web.config的原始配置信息:
C# code

<connectionStrings>
   <add name="mrOnLineExamConnectionString3" connectionString="Data Source=localhost.;Initial Catalog=mrOnLineExam;User ID=sa;password=123456;" providerName="System.Data.SqlClient"/>
   <add name="mrOnLineExamConnectionString4" connectionString="Data Source=localhost.;Initial Catalog=mrOnLineExam;User ID=sa;password=123456;" providerName="System.Data.SqlClient"/>
</connectionStrings>

为什么这里两个代码要重复用?
初学没多久,希望各位好友踊跃出手相教!

作者: lonely9292   发布时间: 2011-12-11

晕,特别标明的颜色在代码里面显示不出来。。。。

作者: lonely9292   发布时间: 2011-12-11

作者: Sandy945   发布时间: 2011-12-12