无法在 ASP.NET C# 中执行 SQL 脚本 - 但可以查询
Unable to execute SQL script within ASP.NET C# - But can Query
我有一段代码可以检查您的本地数据库中是否存在特定数据库,如果不存在,则使用 sql 脚本 运行s。检查数据库是否存在的查询有效,但每当我尝试执行脚本时,我在代码
时连接失败
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 服务器管理工作室中手动设置了 运行 脚本,它在创建整个数据库时有效。当我 运行 它在我的代码中时,我无法连接到服务器,但我最初可以查询它?这是没有意义的。
任何建议将不胜感激。
代码
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;
}
真的很好奇为什么第二个代码有效。谢谢大家的帮助
将两个连接分解为不同的方法,运行 首先创建部分以确定是否仍然出错。像这样但有更好的错误处理:
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;
}
}
我有一段代码可以检查您的本地数据库中是否存在特定数据库,如果不存在,则使用 sql 脚本 运行s。检查数据库是否存在的查询有效,但每当我尝试执行脚本时,我在代码
时连接失败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 服务器管理工作室中手动设置了 运行 脚本,它在创建整个数据库时有效。当我 运行 它在我的代码中时,我无法连接到服务器,但我最初可以查询它?这是没有意义的。 任何建议将不胜感激。
代码
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;
}
真的很好奇为什么第二个代码有效。谢谢大家的帮助
将两个连接分解为不同的方法,运行 首先创建部分以确定是否仍然出错。像这样但有更好的错误处理:
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;
}
}