【发布时间】:2020-06-24 17:28:59
【问题描述】:
手头的问题:无法使用可与服务器资源管理器连接工具一起使用但不适用于我的 WPF 应用程序的连接字符串连接到我的 sql 服务器数据库。
我在端口 49278 连接到 sql server "US06S-SQLSRV",数据库名称是 "Solutions"。我创建了一个需要连接到此服务器的应用程序,但担心服务器将来可能会移动,因此我尝试动态更改此字符串以供将来使用。
这是从连接工具生成的连接字符串:
Data Source=US06S-SQLSRV,49278;Initial Catalog=Solutions;Integrated Security=True
我已将此字符串复制到我的 App.Config 文件中,并在用户登录后尝试测试连接,如下所示:
App.Config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<clear/>
<add name ="DatabaseConnStringSO"
connectionString ="Data Source=US06S-SQLSRV,49278;Initial Catalog=Solutions;Integrated Security=True"/>
</connectionStrings>
</configuration>
DatabaseHelper.CS
public static string sql;
public static SqlConnection conn = new SqlConnection();
public static SqlCommand cmd = new SqlCommand(sql, conn);
public static SqlDataReader reader;
public static SqlDataAdapter sqlDataAdapter;
public static string DataSource = @"US06S-SQLSRV";
public static string GetConnectionStrings(string Name)
{
string strConnx = ConfigurationManager.ConnectionStrings[Name].ToString();
return strConnx;
}
public static void OpenConnection()
{
try
{
if (conn.State == ConnectionState.Closed)
{
conn.ConnectionString = GetConnectionStrings("DatabaseConnStringSO");
conn.Open();
MessageBox.Show("Solutions Database connection successful press 'OK' to proceed.", "Successful connection", MessageBoxButton.OK, MessageBoxImage.Exclamation);
}
}
//+Environment.NewLine + "Description: " + Exception.Message.ToString()
catch (Exception ex)
{
MessageBox.Show("Solutions Database ( " + DataSource + " connection unsuccessful, please seak a MFG personnel to assist in addressing this issue via the configuration window."
+ Environment.NewLine + "Description: " + ex.Message.ToString(), "Unsucessful database connnection, error: 100",
MessageBoxButton.OK, MessageBoxImage.Error);
}
}
这是我得到的错误:
System.Data.SqlClient.SqlException: '建立与 SQL Server 的连接时发生与网络相关或特定于实例的错误。服务器未找到或无法访问。验证实例名称是否正确以及 SQL Server 是否配置为允许远程连接。 (提供者:TCP 提供者,错误:0 - 数据库查找期间发生不可恢复的错误。)'
任何帮助都将不胜感激。
我尝试过的事情:
- 将字符串硬编码到命令中。
- 通过防火墙规则允许端口
- 检查是否可以通过 Sql Server management studio 访问服务器(它同时使用 IP 地址和服务器名称)
- 在连接字符串中使用 IP 地址。
- 使用此数据库创建一个表适配器(当我尝试以这种方式预览数据库但查询从表设计器视图中工作时会产生不同的错误)。
- 是的,表适配器正在使用相同的连接字符串。
- 在服务器上启用 TCP/IP
- 确保在服务器上启用了远程连接
最后我想用一个动态字符串连接到这个数据库。
已编辑以显示进一步的操作: PowerShell结果
Test-NetConnection -Port 49278-ComputerName US08S-SQLSRV
- 计算机名:US06S-SQLSRV
- 远程地址:173.18.167.19
- 远程端口:49278
- 接口别名:以太网 2
- 源地址:173.18.168.193
- TcpTestSucceeded : 真
【问题讨论】:
-
ConfigurationManager.ConnectionStrings[Name].ConnectionString!!! -
@T.S.该连接字符串看起来不错
Server是Data Source的同义词,请参阅docs.microsoft.com/en-us/dotnet/api/…。在 Powershell 中运行Test-NetConnection -Port 49278 -ComputerName US06S-SQLSRV并将输出添加到问题中。 -
检查是否在 sql server 设置中启用了 TCP-IP 协议
-
@Babbillumpa TCP-IP 已启用,否则 Sql Server Management Studio 将无法连接
-
@Neil 进行了更改,但这不是错误的原因。我认为这两种检索字符串的方法都很好。
标签: c# sql sql-server wpf visual-studio-2019