【问题标题】:Unable to execute SQL script within ASP.NET C# - But can Query无法在 ASP.NET C# 中执行 SQL 脚本 - 但可以查询
【发布时间】:2015-10-23 20:02:48
【问题描述】:

我有一段代码检查本地数据库中是否存在特定数据库,如果不存在,则运行 sql 脚本。检查数据库是否存在的查询有效,但每当我尝试执行脚本时,代码连接失败

server.ConnectionContext.ExecuteNonQuery(script);

被执行。 错误:

{Microsoft.SqlServer.Management.Common.ConnectionFailureException: Failed to connect to server Data Source=(localdb)\v11.0;Integrated Security=True;. ---> System.Data.SqlClient.SqlException: 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: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, Boolean withFailover)
   at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover)
   at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout)
   at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance)
   at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData)
   at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
   at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
   at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
   at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
   at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
   at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
   at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry)
   at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
   at System.Data.SqlClient.SqlConnection.Open()
   at Microsoft.SqlServer.Management.Common.ConnectionManager.InternalConnect(WindowsIdentity impersonatedIdentity)
   at Microsoft.SqlServer.Management.Common.ConnectionManager.Connect()
   --- End of inner exception stack trace ---
   at Microsoft.SqlServer.Management.Common.ConnectionManager.Connect()
   at Microsoft.SqlServer.Management.Common.ConnectionManager.PoolConnect()
   at Microsoft.SqlServer.Management.Common.ServerConnection.ExecuteNonQuery(String sqlCommand, ExecutionTypes executionType)
   at Microsoft.SqlServer.Management.Common.ServerConnection.ExecuteNonQuery(String sqlCommand)
   at developer1SVC.Core.DataAccess.DatabaseHelper.CheckForDatabaseAndCreate() in c:\DEV\CODE\developer1SVC2\product\app\developer1SVC.Core\DataAccess\DatabaseHelper.cs:line 74
   at Developer1.Core.Service.Developer1Service.createAccount(AccountActivationDto account) in c:\DEV\CODE\developer1SVC2\product\app\developer1SVC.Core\Service\Developer1Service.cs:line 74}

我在 sql server management studio 中手动运行了脚本,它在创建整个数据库时工作。当我在我的代码中运行它时,我无法连接到服务器,但我最初可以查询它?这是没有意义的。 任何建议将不胜感激。

代码

 public static string CheckForDatabaseAndCreate()
        {
            string testConnection = Config.testConn;

            SqlConnection sqlConnection1 = new SqlConnection(testConnection);
            SqlCommand cmd = new SqlCommand();
            SqlDataReader reader;
            cmd.CommandText = "Select * from sys.databases Where name = 'DEV_WebSystems2'";
            cmd.CommandType = CommandType.Text;
            cmd.Connection = sqlConnection1;

            sqlConnection1.Open();

            reader = cmd.ExecuteReader();
            if (reader.HasRows)
            {
                return ("Database Exists");
            }
            FileInfo file = new FileInfo(databaseScript);
            string script = file.OpenText().ReadToEnd();
            Server server = new Server(new ServerConnection(testConnection));
            server.ConnectionContext.ExecuteNonQuery(script);
            sqlConnection1.Close();
            return ("Database does not exist and was Created");
        }

有效的新代码

public static string CheckForDatabaseAndCreate()
        {
            string testConnection = Config.testConn;

            bool databaseFound = FindDatabase();
            if (databaseFound)
            {
                return "Database Found";
            }
            else
            {
                bool databaseCreated = CreateDatabase();
                return "Database Created";
            }
        }



 private static bool FindDatabase()
    {
        using (var sqlConnection = new SqlConnection(Config.testConn))
        {
            sqlConnection.Open();
            var sqlCommand = new SqlCommand
            {
                CommandText = "Select * from sys.databases Where name = 'DEV_WebSystems2'",
                CommandType = CommandType.Text,
                Connection = sqlConnection
            };
            SqlDataReader reader;
            using (reader = sqlCommand.ExecuteReader())
            {
                if (reader.HasRows)
                {
                    return true;
                }
            }
            return false;
        }
    }

    public static bool CreateDatabase()
    {
        using (var sqlConnection = new SqlConnection(Config.testConn))
        {
            FileInfo file = new FileInfo(databaseScript);
            string script = file.OpenText().ReadToEnd();
            var server = new Server(new ServerConnection(sqlConnection));
            server.ConnectionContext.ExecuteNonQuery(script);
        }
        return true;
    }

真的很好奇为什么第二个代码有效。谢谢大家的帮助

【问题讨论】:

  • 试一试。在使用第二个连接之前关闭第一个连接。
  • 那行不通。不过感谢您的建议。 connectionString 是正确的,但似乎我无法运行脚本。我已经测试了第一个 select 语句是有效的。
  • Web 应用程序是否在您的凭据或其他可能无权访问 SQL Server 的身份(如 NETWORK_SERVICE)下运行?
  • 如果这是真的,我如何查询数据库并读取它但无法写入它?我只使用 Windows 身份验证并为管理工作室提供该数据源,我可以查看服务器。我还编写了存储过程来创建对象,并且可以这样做但不能运行脚本
  • 你检查过“databaseScript”文件的内容吗?它可能对另一个服务器实例有一些引用。

标签: c# asp.net sql-server database-connection connection-string


【解决方案1】:

将这两个连接拆分为不同的方法并首先运行创建部分以确定是否仍然出错。类似这样的东西,但有更好的错误处理:

public static bool CheckForDatabase()
{
    using ( var sqlConnection = new SqlConnection( ConfigurationManager.ConnectionStrings["YourConnectionStringNameFromWebConfig"].ConnectionString))
    {
        var sqlCommand = new SqlCommand
        {
            CommandText = "Select * from sys.databases Where name = 'DEV_WebSystems2'",
            CommandType = CommandType.Text,
            Connection = sqlConnection
        };

        sqlConnection.Open();

        using (var reader = sqlCommand.ExecuteReader())
        {
            if (reader.HasRows)
            {
                return true;
            }
        }

        return false;
    }
}

public static bool Create()
{
    try
    {
        using (var sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["YourConnectionStringNameFromWebConfig"].ConnectionString))
        {
            FileInfo file = new FileInfo(@"C:\Users\yourName\Desktop\test.sql");
            string script = file.OpenText().ReadToEnd();
            var server = new Server(new ServerConnection(sqlConnection));
            server.ConnectionContext.ExecuteNonQuery(script);
        }

        return true;
    }
    catch (Exception exception)
    {
        Log.Error(exception);
        return false;
    }
}

【讨论】:

  • 无论出于何种原因,您的解决方案都对我有用。给你的道具
猜你喜欢
  • 2017-01-07
  • 1970-01-01
  • 1970-01-01
  • 2013-12-15
  • 1970-01-01
  • 2020-06-24
  • 1970-01-01
  • 1970-01-01
  • 2019-06-18
相关资源
最近更新 更多