0

我有一塊代碼,用於檢查本地數據庫中是否存在特定數據庫,如果不存在,是否運行sql腳本。檢查數據庫是否存在的查詢工作,但每當我嘗試和執行腳本我無法連接時代碼無法在ASP.NET C#中執行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; 
    } 

真的很好奇,爲什麼第二次代碼工作。謝謝大家的幫助

+0

只是一個嘗試。在使用第二個連接之前關閉第一個連接。 – Steve

+0

這沒有奏效。感謝您的建議,但。 connectionString是正確的,但似乎我無法運行腳本。我已經測試了第一條select語句正在工作。 – devzim

+0

Web應用程序是否在您的憑據或其他身份(如NETWORK_SERVICE)下運行,可能沒有SQL Server權限? –

回答

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; 
    } 
} 
+0

不管出於什麼原因您的解決方案爲我工作。道具給你的男人 – devzim