【问题标题】:Can't connect to SQL Server with a created web service无法使用已创建的 Web 服务连接到 SQL Server
【发布时间】:2016-05-02 05:02:01
【问题描述】:

我正在尝试自学一些有关 Web 服务的基础知识并设置一个简单的应用程序,该应用程序只访问 SQL 服务器并从数据库中提取一个项目。

但我在尝试连接时收到此错误:

“命名管道提供程序,错误:40 - 无法打开与 SQL Server 的连接)---> System.ComponentModel.Win32Exception:找不到网络路径”

我将此连接字符串用于其他解决方案,它可以正常工作,但不适用于 Web 服务,并且在搜索 Stack 时我找不到适合此问题的解决方案。

      <connectionStrings>
<add name="Snafoo" connectionString="Data Source=HOCHBAUM|SQLEXPRESS; Initial Catalog=Snafoo;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />

这里是网络服务:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Services;
    using System.Data;
    using System.Data.SqlClient;
    using System.Configuration;


    namespace SnafooWebService
    {
/// <summary>
/// Summary description for SnafooService
/// </summary>
[WebService(Namespace = "Snafoo")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
// [System.Web.Script.Services.ScriptService]
public class SnafooService : System.Web.Services.WebService
{


    [WebMethod()]
    public Snacks GetSnackByID(int ID)
    {
        //Retrieve connection String from Web.config
        string cs = ConfigurationManager.ConnectionStrings["Snafoo"].ConnectionString;
        //Create a SQL connection object
        using (SqlConnection con = new SqlConnection(cs))
        {
            //This object executes stored procedure in SQL
            SqlCommand cmd = new SqlCommand("spGetSnackByID", con);
            cmd.CommandType = CommandType.StoredProcedure;
            SqlParameter parameter = new SqlParameter("@Id", ID);
            cmd.Parameters.Add(parameter);
            Snacks snack = new Snacks();
            //Opens the cconection
            con.Open();
            SqlDataReader reader = cmd.ExecuteReader();
            //Retrieve column values and populate properties of snack object
            while (reader.Read())
            {
                snack.id = Convert.ToInt32(reader["ID"]);
                snack.name = reader["name"].ToString();
                snack.location = reader["location"].ToString();

            }
            return snack;

        }

    }

}
    }

【问题讨论】:

  • "HOCHBAUM|SQLEXPRESS" 好像错了,试试"HOCHBAUM\SQLEXPRESS"
  • 你有答案!有效!盯着它看了好几个小时,完全错过了,有第二双眼睛真好!

标签: asp.net sql-server web-services


【解决方案1】:

如果您不使用本地 SQL Server
1-如果 SQL 浏览器已启动,请检查您的服务
2-在您的 SQl 服务器配置管理器上检查您是否启用了 TCP/IP 和名称管道以便能够远程访问您的数据库
3-如果您的 sql 服务器不是本地的,您可以使用 IP 和端口访问它,例如 xxx.xxx.xxx.xxx\SQLEXPRESS,1029 ,您可以在其中从您的 sql 配置管理器更改端口。
4-确保在您的连接字符串中输入用户名和密码 (uid=sa;password=mmmm)
希望这些笔记对你有所帮助

【讨论】:

    猜你喜欢
    • 2021-02-16
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-21
    • 1970-01-01
    • 2017-01-06
    相关资源
    最近更新 更多