【发布时间】:2021-10-02 16:48:56
【问题描述】:
我在 AWS Windows 2016 服务器上。它预装了 SQL Server 2016。
我有一个 .NET 4.8 网站,我正在尝试将网站(在 Web 服务器上)连接到 SQL Server 实例(也安装在 Web 服务器上)。
我有一个简单的 C# 函数来告诉我我的连接字符串是否有效(我尝试过的所有操作都返回 false)。
public static bool IsServerConnected(string connectionString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
try
{
connection.Open();
return true;
}
catch (SqlException)
{
return false;
}
}
}
private static string connect = ConfigurationManager.ConnectionStrings["db"].ConnectionString;
public static string connDb
{
get { return connect; }
set { connect = value; }
}
// Usage:
bool TestConnection = IsServerConnected(connDb);
这是来自我的web.config 文件(连接字符串)
[出于隐私原因,我只在字符串中包含 ****,我使用了实际的 SQL Server 名称]:
<connectionStrings>
<add name="db"
connectionString="Data Source=EC2AMAZ-84****;Initial Catalog=testdb;Integrated Security=True;Trusted_Connection=Yes;"
providerName="System.Data.SqlClient" />
</connectionStrings>
这是来自 SQL Server Management Studio 的屏幕(我从网站所在的同一 Windows Server 访问):
谁能帮帮我?我应该如何设置我的连接字符串?
编辑
根据我在下面收到的一些帮助,这是我目前所处的位置:
- 我运行了脚本来创建新的登录名和角色
- 命令成功完成后,我退出 SSMS,然后使用服务重新启动 SSMS(见图 2)
- 我使用以下凭据登录 SSMS:“MyUser”和“P@ssword01”
- 我收到一条错误消息,指出登录成功但共享内存提供程序错误(SQL Server 错误 223)
【问题讨论】:
-
集成安全意味着您正在使用 Windows 身份验证连接到数据库,最大的问题是,您的程序使用什么 Windows 凭据运行?我通常为用于特定应用程序的程序创建 SQL 登录名,并在连接字符串中指定用户和密码。此外,如果您可以输出 SqlException 消息以查看发生了什么,这将有所帮助
-
@Alex 感谢您的意见!这是我收到的错误消息:
ERROR: 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) -
输出 Environment.UserName 并查看它使用的凭据
-
DefaultAppPool -
好的,这是个问题,它正在使用应用程序池身份!您不能在连接字符串中传递 Windows 用户名和密码来登录 SQL Server。所以我建议你为此创建一个 SQL 登录并在连接字符串中传递用户和密码。
标签: c# sql sql-server connection-string windows-server