简体   繁体   English

.NET 核心 - 无法连接 SQL 服务器

[英].NET Core - not able to connect SQL Server

I am using Visual Studio 2019 and using SQL Server docker image from this website我正在使用 Visual Studio 2019 并使用来自本网站的 SQL 服务器 docker 图像

I created docker container by docker run -d --name MySQLServer -e 'ACCEPT_EULA=Y' -e 'SA_PASSWORD=Password123@jkl#' -p 1433:1433 microsoft/mssql-server-linux我通过docker run -d --name MySQLServer -e 'ACCEPT_EULA=Y' -e 'SA_PASSWORD=Password123@jkl#' -p 1433:1433 microsoft/mssql-server-linux创建了 docker 容器

I also connect the SQL Server using Azure Data Studio我还使用Azure Data Studio连接了 SQL 服务器

I have created migration script by command add-migration Initial我已经通过命令add-migration Initial创建了迁移脚本

When I run below command in package manager console :当我在package manager console中运行以下命令时:

PM> update-database

Build started...
Build succeeded.
Microsoft.Data.SqlClient.SqlException (0x80131904): 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: TCP Provider, error: 35 - An internal exception was caught)
 ---> System.Net.Internals.SocketExceptionFactory+ExtendedSocketException (00000005, 0xFFFDFFFF): nodename nor servname provided, or not known
   at System.Net.Dns.GetHostEntryOrAddressesCore(String hostName, Boolean justAddresses)
   at System.Net.Dns.GetHostAddresses(String hostNameOrAddress)
   at Microsoft.Data.SqlClient.SNI.SNITCPHandle.Connect(String serverName, Int32 port, TimeSpan timeout, Boolean isInfiniteTimeout, String cachedFQDN, SQLDNSInfo& pendingDNSInfo)
   at Microsoft.Data.SqlClient.SNI.SNITCPHandle..ctor(String serverName, Int32 port, Int64 timerExpire, Object callbackObject, Boolean parallel, String cachedFQDN, SQLDNSInfo& pendingDNSInfo)
   at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at Microsoft.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, Boolean withFailover, SqlAuthenticationMethod authType)
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover)
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout)
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance)
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, Boolean applyTransientFaultHandling, String accessToken, DbConnectionPool pool)
   at Microsoft.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
   at Microsoft.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
   at Microsoft.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
   at Microsoft.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
   at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
   at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
   at Microsoft.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
   at Microsoft.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
   at Microsoft.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
   at Microsoft.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry, SqlConnectionOverrides overrides)
   at Microsoft.Data.SqlClient.SqlConnection.Open(SqlConnectionOverrides overrides)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerConnection.OpenDbConnection(Boolean errorsExpected)
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternal(Boolean errorsExpected)
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open(Boolean errorsExpected)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerDatabaseCreator.<>c__DisplayClass18_0.<Exists>b__0(DateTime giveUp)
   at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.<>c__DisplayClass12_0`2.<Execute>b__0(DbContext c, TState s)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
   at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.Execute[TState,TResult](IExecutionStrategy strategy, TState state, Func`2 operation, Func`2 verifySucceeded)
   at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.Execute[TState,TResult](IExecutionStrategy strategy, TState state, Func`2 operation)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerDatabaseCreator.Exists(Boolean retryOnNotExists)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerDatabaseCreator.Exists()
   at Microsoft.EntityFrameworkCore.Migrations.HistoryRepository.Exists()
   at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
   at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.UpdateDatabase(String targetMigration, String connectionString, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabaseImpl(String targetMigration, String connectionString, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabase.<>c__DisplayClass0_0.<.ctor>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
ClientConnectionId:00000000-0000-0000-0000-000000000000
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: TCP Provider, error: 35 - An internal exception was caught)

Code代码

appsettings.json appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "ConStr": "Data Source=My_DB_local;Initial Catalog=TipsDemo;Persist Security Info=True;User ID=sa;Password=Password123@jkl#"
  },
  "JWT": {
    "ValidAudience": "User",
    "ValidIssuer": "http://localhost:1433",
    "Secret": "ThisMySecretKey123"
  }
}

I am refering to this project我指的是这个项目
https://github.com/mhassan90/AspCoreAPI/tree/master/TestAspCore/TestAspCore https://github.com/mhassan90/AspCoreAPI/tree/master/TestAspCore/TestAspCore

How to fix it?如何解决?

I think to update databases you need to create a database first.我认为要更新数据库,您需要先创建一个数据库。 If you have not installed SQL Server I recommend you to install SQL Server from microsoft store at first.如果您还没有安装 SQL 服务器,我建议您首先从 microsoft store 安装 SQL 服务器。

  1. To create a database at SQL Server click on 'view' at toolbar select 'SQL Server object explorer'.要在 SQL 服务器上创建数据库,请单击工具栏 select 'SQL Server object explorer'上的“查看”。
  2. that will open a window at the left-Up corner, there will be a SQL Server at the top of that move pointer there will be given Object Explorer or SQL Server object explorer; that will open a window at the left-Up corner, there will be a SQL Server at the top of that move pointer there will be given Object Explorer or SQL Server object explorer; click on that.点击那个。
  3. Now the structure of that will be changed open SQL Server then click on open any localdb database something is given then There will have databases folder.现在将更改其结构打开 SQL 服务器然后单击打开任何 localdb 数据库,然后将有数据库文件夹。
  4. Right click on databases and create a new database and then create a table inside that database.右键单击数据库并创建一个新数据库,然后在该数据库中创建一个表。

Another way you can do that.另一种方法可以做到这一点。

  1. Install microsoft sql server manager studio.安装 microsoft sql 服务器管理器工作室。
  2. Then connect to sql server engine.然后连接到 sql 服务器引擎。
  3. Right click on database and create a database and then create table.右键单击数据库并创建一个数据库,然后创建表。

then again try your commands to update the database.然后再次尝试您的命令来更新数据库。 I hope that will help you.我希望这会对你有所帮助。

The problem is in your database connection string, I have modified it, and it works.问题出在您的数据库连接字符串中,我已对其进行了修改,并且可以正常工作。 I have removed the user name and password part.我已经删除了用户名和密码部分。 Check if the user you are using exist and the password is correct.检查您使用的用户是否存在以及密码是否正确。

The data source should be Data Source=localhost instead of My_DB_local .数据源应该是Data Source=localhost而不是My_DB_local

在此处输入图像描述

"ConnectionStrings": {
    "ConStr": "Data Source=localhost;Initial Catalog=TipsDemo;Persist Security Info=True;User ID=sa;Password=Password123@jkl#"
  },

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法从 RHEL 7 上的 .Net 核心应用程序连接到 SQL Server 数据库 - Not able to connect to a SQL Server db from .Net core app on RHEL 7 无法从.net核心应用程序连接到Sql Server - Cannot connect to Sql server from .net core application 无法从 NET Core 连接到 SQL Server Express - Cannot connect to SQL Server Express from NET Core 如何连接到现有数据库? .NET Core API和SQL Server 2012 - How to connect to existing database? .NET Core API & SQL Server 2012 如何使用ASP Net Core 2连接到SQL Server 2008? - How to connect to SQL Server 2008 with asp net core 2? .NET Core 无法连接到远程 SQL Server 数据库 - .NET Core can't connect to remote SQL Server database .Net Core 3.1.5 无法连接到 API - .Net Core 3.1.5 not able to connect to API Unable to connect to Azure SQL database from my ASP.NET Core Web API application but able to connect to db from Management Studio - Unable to connect to Azure SQL database from my ASP.NET Core Web API application but able to connect to db from Management Studio 无法使用.NET Core 2.0在本地连接到Ubuntu 16.04服务器上的SQL Server - Unable to connect locally to SQL Server on Ubuntu 16.04-server using .NET Core 2.0 如何从在容器中运行的 ASP.NET 核心应用程序连接到具有集成安全性的 Windows 服务器上的 SQL 服务器 - How to connect from ASP.NET Core application running in a container to SQL Server on Windows Server with Integrated Security
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM