Reputation: 7819
I wrote class by Microsoft samples but it doesn't work:
public class Database
{
private bool Create()
{
string path = GetPath();
Debug.WriteLine("Path: " + path);
try
{
string connectionString = string.Format(@"Data Source=(LocalDB)\v11.0;Initial Catalog=master;Integrated Security=True");
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand cmd = connection.CreateCommand();
DetachDatabase(DatabaseName);
cmd.CommandText = string.Format("CREATE DATABASE {0} ON (NAME = N'{0}', FILENAME = '{1}')", DatabaseName, path);
cmd.ExecuteNonQuery();
}
if (File.Exists(path)) return true;
else return false;
}
catch
{
throw;
}
}
public static bool DetachDatabase(string dbName)
{
try
{
string connectionString = string.Format(@"Data Source=(LocalDB)\v11.0;Initial Catalog=master;Integrated Security=True");
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand cmd = connection.CreateCommand();
cmd.CommandText = string.Format("exec sp_detach_db '{0}'", dbName);
cmd.ExecuteNonQuery();
return true;
}
}
catch
{
return false;
}
}
private string GetPath()
{
string filename = System.Reflection.Assembly.GetExecutingAssembly().CodeBase;
return new Uri(Path.GetDirectoryName(filename)).LocalPath + "\\" + DatabaseName + DatabaseType;
}
}
Acrashes with errors when it calls connection.Open()
:
Вызвано исключение: "System.Data.SqlClient.SqlException" в System.Data.dll Вызвано исключение: "System.Data.SqlClient.SqlException" в SK.exe "SK.vshost.exe" (CLR v4.0.30319: SK.vshost.exe). Загружено "C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Transactions.resources\v4.0_4.0.0.0_ru_b77a5c561934e089\System.Transactions.resources.dll". Сборка модуля выполнена без символов. System.Transactions Critical: 0 : http://msdn.microsoft.com/TraceCodes/System/ActivityTracing/2004/07/Reliability/Exception/UnhandledНеобработанное исключениеSK.vshost.exeSystem.Data.SqlClient.SqlException, System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089При установлении соединения с SQL Server произошла ошибка, связанная с сетью или с определенным экземпляром. Сервер не найден или недоступен. Убедитесь, что имя экземпляра указано правильно и что на SQL Server разрешены удаленные соединения. (provider: SQL Network Interfaces, error: 50 - Произошла ошибка Local Database Runtime.Невозможно создать автоматический экземпляр. Дополнительные сведения об ошибке см. в журнале событий приложений Windows. ) в System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, DbConnectionPool pool, String accessToken, Boolean applyTransientFaultHandling) в System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)...
In Russian it says that the server not found or not available
.
P.S. I retried few variants that I found but it doesn't work all same.
Upvotes: 0
Views: 158
Reputation: 750
Сервер не найден или недоступен. Убедитесь, что имя экземпляра указано правильно и что на SQL Server разрешены удаленные соединения.
This means you can't connect to your sql server. Your connection string is wrong.
Upvotes: 1