Reputation: 153
I have a block of code which checks if a specific database exists within your local database and if not, a sql script runs. The query for checking if the database exists works but whenever i try and execute the script I get failed to connect when the code
server.ConnectionContext.ExecuteNonQuery(script);
is executed. Error:
{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}
I have ran the script manually in sql server management studio and it works when creating the entire database. When i run it in my code I cant connect to the server but i can query it initially? this makes no sense. Any advice would be much appreciated.
Code
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");
}
New Code which worked
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;
}
Really curious why the second code worked. Thank you for everyones help
Upvotes: 1
Views: 1710
Reputation: 51
Break out the two connections into different methods and run the create portion first to determine if that still errors out. Something like the this but with better error handling:
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;
}
}
Upvotes: 2