【问题标题】:Why can't I connect to SQL Server 2016 Express from VS为什么我无法从 VS 连接到 SQL Server 2016 Express
【发布时间】:2016-12-17 05:58:25
【问题描述】:

我是新手。我正在做一个 ASP.NET 教程,但我无法从 VS 连接到 SQL Server 2016 Express。我收到以下错误:

An exception of type 'System.InvalidOperationException' occurred in System.Data.dll but was not handled in user code

Additional information: Instance failure.

这是我的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace tree_view_control_tutorial_2
{
    public partial class WebForm4 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GetData(null);
            }
        }

        private void GetData(string searchTerm)
        {
            string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
            using (SqlConnection con = new SqlConnection(cs))
            {
                SqlCommand cmd = new SqlCommand("spSearchStudents", con);
                cmd.CommandType = CommandType.StoredProcedure;

                SqlParameter searchParameter = new SqlParameter("@SearchTerm", searchTerm);
                cmd.Parameters.Add(searchParameter);
                con.Open();
                GridView1.DataSource = cmd.ExecuteReader();
                GridView1.DataBind();
            }
        }
    }
} 

我该如何解决这个问题?谢谢!

【问题讨论】:

  • 您是否尝试在 con.Open() 行之后调试应用程序?
  • 是的。它没有显示错误。
  • 您可以使用 SSMS 在代码之外进行连接吗?

标签: sql asp.net ado.net


【解决方案1】:

想通了!我的连接字符串在 Web.config 页面上,它是 XML,而不是 C#,所以数据源应该是“.\SQLEXPRESS”(只有一个 \!)

【讨论】:

    【解决方案2】:

    您在 web.config 中的连接字符串应如下所示。

    <connectionStrings>
        <add name="DBCS" 
             connectionString="Data Source=.\\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True" 
             providerName="System.Data.SqlClient"/>
    </connectionStrings>
    

    由于您遇到实例失败,这是SQL服务器实例的创建问题,只需在您执行应用程序时检查SQL服务器是否已启动并运行。

    要检查服务,只需在运行对话窗口中输入 services.msc

    【讨论】:

    • 我检查了 services.msc,服务器正在运行。我试过你的连接字符串(用我的数据库名称替换 Northwind),我得到了同样的错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-01
    • 1970-01-01
    • 2021-05-14
    相关资源
    最近更新 更多