繁体   English   中英

无法连接到本地 SQL Server 数据库

[英]Trouble connecting to local SQL Server database

只是尝试在 Visual Studio 中做一个简单的本地数据库连接到 Microsoft SQL Server。 试图弄清楚为什么它没有连接。 我专门为此创建了一个用户,并拥有正确的用户名和密码。 我故意省略了用户 ID 和密码。 似乎在我的连接字符串中抛出错误,我做错了什么?

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

我的代码:

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

namespace Assetmvc
{
    public partial class SearchPage : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            // Connect to the db
            string connStr = "Server=localhost;Database=AssetTracking;User Id=;Password=; ";
            SqlConnection conn = new SqlConnection(connStr);
            conn.Open();

            // Create a command
            SqlCommand cmd = new SqlCommand("SELECT [EmployeeId],[FirstName],[LastName],[HiredDate],[FiredDate],[CurrentItems],[SupervisorId],[SupervisorName] From [dbo].Employees");
            cmd.CommandType = System.Data.CommandType.Text;
            cmd.Connection = conn;

            string temp = "";

            // Read from database
            SqlDataReader reader = cmd.ExecuteReader();

            while(reader.Read())
            {
                temp += reader["EmployeeId"].ToString();
                temp += reader["FirstName"].ToString();
                temp += reader["LastName"].ToString();
                temp += reader["HiredDate"].ToString();
                temp += reader["FiredDate"].ToString();
                temp += reader["CurrentItems"].ToString();
                temp += reader["SupervisorId"].ToString();
                temp += reader["SupervisorName"].ToString();
                temp += 

                temp += "<br/>";
            }

            conn.Close();

            lbl_test.Text = temp; 
        }
    }
}

如果您使用的是 SQL Server Express并在安装时使用了所有默认值,那么您有一个名为SQLEXPRESS的 SQL Server命名实例- 因此,您需要使用此连接字符串:

string connStr = "Server=localhost\\SQLEXPRESS;Database=AssetTracking;User Id=;Password=; ";

请注意,您需要使用localhost\\SQLEXPRESS连接到实例名称为SQLEXRPESS命名实例

经过一整天的故障排除后,本指南有很大帮助。

https://success.scribesoft.com/s/article/Named-Pipes-Provider-Error-40

尽管这样做之后我最终只使用了在 Sql server explorer 中单击我的服务器后属性框中提供的连接字符串。

我要感谢所有没有投票但实际上帮助过我的人,我真的很感激。 我将 Marc_S 标记为答案,但想为可能阅读此内容的任何其他人添加此内容。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM