繁体   English   中英

使用IIS 7连接到SQL时出错

[英]Error connecting to SQL with IIS 7

在IIS中工作时,我最近在该处启动了一个应用程序。 当我尝试“浏览”应用程序时,它抛出了以下错误,该错误先前已另一位用户的讨论中:

The network path was not found

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.ComponentModel.Win32Exception: The network path was not found

Source Error: 


Line 34:                 {
Line 35:                     EventLogger.LogEvent(ex);
Line 36:                     throw ex;
Line 37:                 }
Line 38:                 finally

Source File: c:\Program Files (x86)\Jenkins\jobs\IBT\workspace\iLaundry.IBT\Data\DatabaseUpdater.cs    Line: 36 

Stack Trace: 


[Win32Exception (0x80004005): The network path was not found]

[SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)]
   iLaundry.IBT.Data.DatabaseUpdater.GetCurrentVersion() in c:\Program Files (x86)\Jenkins\jobs\IBT\workspace\iLaundry.IBT\Data\DatabaseUpdater.cs:36
   iLaundry.IBT.Data.DatabaseUpdater.ExecuteUpdates() in c:\Program Files (x86)\Jenkins\jobs\IBT\workspace\iLaundry.IBT\Data\DatabaseUpdater.cs:188
   iLaundry.IBT.Data.IBTData..cctor() in c:\Program Files (x86)\Jenkins\jobs\IBT\workspace\iLaundry.IBT\Data\IBTData.cs:40

[ApplicationException: Cannot connect to the database]
   iLaundry.IBT.Data.IBTData..cctor() in c:\Program Files (x86)\Jenkins\jobs\IBT\workspace\iLaundry.IBT\Data\IBTData.cs:45

我已按照先前接受的答案建议更改了连接字符串,但它仍无法解决我的问题。 这是用于将应用程序与数据库连接的C#代码:

C#:

using iLaundry.Utilities;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;

namespace iLaundry.IBT.Data
{
    internal class DatabaseUpdater
    {

        private string connectionString;

        internal DatabaseUpdater(string connectionString)
        {
            this.connectionString = connectionString;
        }

        internal Version GetCurrentVersion()
        {
            using (SqlConnection conn = new SqlConnection(connectionString))
            using (SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM sysobjects WHERE xtype='P' AND [name]='DatabaseVersion'", conn))
            {
                try
                {
                    conn.Open();
                    if ((int)cmd.ExecuteScalar() == 0)
                        return Version.Parse("0.0.0.0");
                    cmd.CommandText = "DatabaseVersion";
                    return Version.Parse((string)cmd.ExecuteScalar());
                }
                catch (Exception ex)
                {
                    EventLogger.LogEvent(ex);
                    throw ex;
                }
                finally
                {
                    conn.Close();
                }
            }
        }

        internal List<string> GetUpdates(Version currentVersion, Version targetVersion)
        {
            List<string> result = new List<string>();

            if (currentVersion == targetVersion)
                return result;

            #region 0.0.0.0 -> 0.0.0.1

            if (currentVersion == Version.Parse("0.0.0.0"))
            {

                // Create List Items with Table
                currentVersion = result.AddUpdate(Version.Parse("0.0.0.1"),
                    @"CREATE TABLE Account (AccountId int primary key identity(1, 1),
UserName varchar(50) not null,
Password varchar(50) not null,
StatusActive bit not null)",

                    @"CREATE TABLE Recharge (RechargeId int primary key identity(1, 1),
AccountId int not null references Account,
RechargeDateTime datetime not null,
ExpiryDateTime datetime not null)",

                    @"CREATE TABLE Branch (BranchId int primary key identity(1, 1),
BranchKey varchar(50) unique not null,
SyncKey uniqueidentifier unique not null)",

                    @"CREATE TABLE Service (ServiceId int primary key identity(1, 1),
OwnerBranchId int not null references Branch,
SyncKey uniqueidentifier unique not null,
Description varchar(200),
StatusActive bit not null)",

                    @"CREATE TABLE [Order] (OrderId int primary key identity(1, 1),
BranchId int not null references Branch,
ExOrderNumber varchar(50) not null)",

                    @"CREATE TABLE OrderService (OrderServiceId int primary key identity(1, 1),
OrderId int not null references [Order],
ServiceId int not null references [Service],
Quantity int not null)",

                    @"CREATE PROCEDURE DatabaseVersion AS SELECT [Version]='0.0.0.0'");
            }

            #endregion


            #region 0.0.0.1 -> 0.0.0.6

            if (currentVersion == Version.Parse("0.0.0.1"))
                currentVersion = result.AddUpdate(
                    Version.Parse("0.0.0.2"),
@"CREATE TABLE Subscription (SubscriptionId int primary key identity(1, 1),
ProviderBranchId int not null references Branch,
ConsumerBranchId int not null references Branch,
RequestDateTime datetime not null,
ApproveDateTime datetime,
RejectDateTime datetime)",
@"ALTER TABLE Branch ADD [Name] varchar(100) not null, IsProvider bit not null default 0, IsConsumer bit not null default 0",
"ALTER TABLE Account ADD CONSTRAINT UQ_Username UNIQUE (Username)",
"ALTER TABLE Branch ADD CONSTRAINT UQ_BranchKey unique (BranchKey)",
"ALTER TABLE Branch ADD CONSTRAINT UQ_SyncKey unique (SyncKey)"
                    );

            if (currentVersion == Version.Parse("0.0.0.2"))
                currentVersion = result.AddUpdate(Version.Parse("0.0.0.3"),
                @"ALTER TABLE [ORDER] ADD [DispatchNumber] int null, [OrderStatusId] int not null default 1",
                @"CREATE TABLE [OrderStatus] (OrderStatusId int primary key identity(1, 1),StatusDescription varchar(50) not null,StatusActive bit not null)",
                @"INSERT [dbo].[ORDERSTATUS] ([StatusDescription], [StatusActive]) VALUES (N'DispatchToProvider', 1)",
                @"INSERT [dbo].[ORDERSTATUS] ([StatusDescription], [StatusActive]) VALUES (N'ReceivedByProvider', 1)",
                @"INSERT [dbo].[ORDERSTATUS] ([StatusDescription], [StatusActive]) VALUES (N'InProgress', 1)",
                @"INSERT [dbo].[ORDERSTATUS] ([StatusDescription], [StatusActive]) VALUES (N'Ready', 1)",
                @"INSERT [dbo].[ORDERSTATUS] ([StatusDescription], [StatusActive]) VALUES (N'DispatchToConsumer', 1)",
                @"INSERT [dbo].[ORDERSTATUS] ([StatusDescription], [StatusActive]) VALUES (N'ReceivedByConsumer', 1)",
                @"INSERT [dbo].[ORDERSTATUS] ([StatusDescription], [StatusActive]) VALUES (N'ReadyForCollection', 1)"
                );

            if (currentVersion == Version.Parse("0.0.0.3"))
                currentVersion = result.AddUpdate(Version.Parse("0.0.0.4"),
                @"CREATE TABLE OrderStatusUpdate (OrderStatusUpdateId int primary key identity(1, 1),
OrderId int not null references [Order],
PreviousOrderStatusId int REFERENCES [OrderStatus],
NewOrderStatusId int NOT NULL REFERENCES [OrderStatus],
ChangeDateTime datetime not null)",
                @"CREATE TRIGGER TR_OrderStatusUpdate ON [Order]
FOR INSERT,UPDATE
AS
    IF EXISTS(SELECT * FROM inserted) BEGIN
        INSERT
        INTO    OrderStatusUpdate
                (OrderId, NewOrderStatusId, ChangeDateTime)
        SELECT  OrderId, OrderStatusId, GETDATE()
        FROM    inserted
    END ELSE BEGIN
        INSERT
        INTO    OrderStatusUpdate
                (OrderId, PreviousOrderStatusId, NewOrderStatusId, ChangeDateTime)
        SELECT  u.OrderId, u.OrderStatusId, i.OrderStatusId, GETDATE()
        FROM    deleted u
                INNER JOIN inserted i ON (u.OrderId = i.OrderId)
    END");

            if (currentVersion == Version.Parse("0.0.0.4"))
                currentVersion = result.AddUpdate(Version.Parse("0.0.0.5"),
                @"INSERT [dbo].[ORDERSTATUS] ([StatusDescription], [StatusActive]) VALUES (N'ReturnedByProvider', 1)");

            if (currentVersion == Version.Parse("0.0.0.5"))
                currentVersion = result.AddUpdate(Version.Parse("0.0.0.6"),
                @"DELETE FROM [OrderStatusUpdate]",
                @"DELETE FROM [OrderService]",
                @"DELETE FROM [Order]",
                @"ALTER TABLE [Order] DROP COLUMN ExOrderNumber, DispatchNumber",
                @"ALTER TABLE [Order] ADD ConsumerOrderNo varchar(50) NOT NULL, ConsumerDispatchNo varchar(50) NOT NULL, ProviderOrderNo varchar(50), ProviderDispatchNo varchar(50)",
                @"CREATE TABLE [OrderServiceAttribute] (OrderServiceAttributeId int identity(1, 1) primary key, [OrderId] int not null references [Order], [Kind] varchar(50) NOT NULL, [Value] varchar(50) NOT NULL)");

            if (currentVersion == Version.Parse("0.0.0.6"))
                currentVersion = result.AddUpdate(Version.Parse("0.0.0.7"),
                @"ALTER TABLE [Order] ADD CONSTRAINT [FK_Order_OrderStatus] FOREIGN KEY ([OrderStatusId]) REFERENCES [OrderStatus] (OrderStatusId)");

            if (currentVersion == Version.Parse("0.0.0.7"))
                currentVersion = result.AddUpdate(Version.Parse("0.0.0.8"),
                @"DROP TABLE [OrderServiceAttribute]",
                @"CREATE TABLE [OrderServiceAttribute] (OrderServiceAttributeId int identity(1, 1) primary key, [OrderServiceId] int not null references [OrderService], [Kind] varchar(50) NOT NULL, [Value] varchar(50) NOT NULL)");


            if (currentVersion == Version.Parse("0.0.0.8"))
                currentVersion = result.AddUpdate(Version.Parse("0.0.0.9"),
                @"ALTER TABLE [OrderService] ALTER COLUMN Quantity float NOT NULL");

            if (currentVersion == Version.Parse("0.0.0.9"))
                currentVersion = result.AddUpdate(Version.Parse("0.0.0.10"),
                @"CREATE TABLE [OrderServiceDispute] (OrderServiceDisputeId int identity(1, 1) primary key, BranchId int not null references [Branch], IsReceived bit NOT NULL, Comment varchar(max))");

            #endregion

            //Next Version to follow here
            return result;
        }

        internal bool ExecuteUpdates()
        {
            Version currentVersion = GetCurrentVersion();
            Version targetVersion = this.GetType().Assembly.GetName().Version;
            if (currentVersion >= targetVersion)
                return true;
            List<string> heal = GetUpdates(currentVersion, targetVersion);
            heal.AddUpdate(targetVersion);

            using (SqlConnection conn = new SqlConnection(connectionString))
            using (SqlCommand cmd = new SqlCommand())
            {
                try
                {
                    cmd.Connection = conn;
                    conn.Open();
                    foreach (string sql in heal)
                    {
#if(DEBUG)
                        System.Diagnostics.Debug.WriteLine(sql);
#endif
                        cmd.CommandText = sql;
                        cmd.ExecuteNonQuery();
                    }
                    EventLogger.LogEvent(string.Format("Successfully updated to version {0}", targetVersion.ToString()));

                    return true;
                }
                catch (Exception ex)
                {
                    EventLogger.LogEvent(ex);
                    return false;
                }
            }

        }
    }

    internal static class DatabaseUpdater_Extensions
    {
        internal static Version AddUpdate(this List<string> updates, Version newVersionNo, params string[] sql)
        {
            updates.AddRange(sql);
            updates.Add(string.Format("ALTER PROCEDURE DatabaseVersion AS SELECT [Version]='{0}'", newVersionNo));
            return newVersionNo;
        }
    }
}

如果您之前曾遇到此错误并能够解决此错误,则对此问题的任何投入,我们将不胜感激。

假设您的连接字符串现在正确-并指向服务器,那么您要以什么用户身份连接数据库? 如果您使用的是Windows身份验证而不是SQL身份验证,则需要将正在运行应用程序的用户添加到数据库中,并确保它具有必要的权限。 您需要添加的用户可能是IISAPPPOOL /默认应用程序池

经过数小时的努力后,该问题的解决方案是进入IIS,而是查看“ Connection String选项卡而不是SQL Server本身。 在IIS访问SQL之后,我只需要通过更改数据源名称来启用连接字符串,如下所示:

在此处输入图片说明

default connection更改为正确的数据源后。 连接完全按照我想要的方式工作。

暂无
暂无

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

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