【发布时间】:2014-03-30 21:19:36
【问题描述】:
我的 WPF 应用程序通过App.config 中的连接字符串连接到 SQL Server 数据库,它可以在本地网络上运行。
我有一个登录屏幕“4 位密码登录”,在输入第四位数字后,我检查了“照常”是否正确。
我的问题是如何检查客户端机器是否连接到服务器?如果不是,我想显示消息。
我不知道我应该从哪里开始:(
希望这一点清楚。 谢谢
【问题讨论】:
标签: c# wpf sql-server-2008
我的 WPF 应用程序通过App.config 中的连接字符串连接到 SQL Server 数据库,它可以在本地网络上运行。
我有一个登录屏幕“4 位密码登录”,在输入第四位数字后,我检查了“照常”是否正确。
我的问题是如何检查客户端机器是否连接到服务器?如果不是,我想显示消息。
我不知道我应该从哪里开始:(
希望这一点清楚。 谢谢
【问题讨论】:
标签: c# wpf sql-server-2008
您可以简单地检查执行检查客户端是否可以打开连接。
从this answer 提取的代码。
/// <summary>
/// Test that the server is connected
/// </summary>
/// <param name="connectionString">The connection string</param>
/// <returns>true if the connection is opened</returns>
private static bool IsServerConnected(string connectionString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
try
{
connection.Open();
return true;
}
catch (SqlException)
{
return false;
}
finally
{
// not really necessary
connection.Close();
}
}
}
【讨论】:
IsServerConnected(); 不起作用。
试试这个
private void ConnectToServer()
{
string sServerName = _fileIO.GetServerInfo("ServerName");
string sSqlInstance = _fileIO.GetServerInfo("SqlInstance");
string sDataBase = _fileIO.GetServerInfo("DataBase");
string sUserID = _fileIO.GetServerInfo("UserID");
string sPassWord = _fileIO.GetServerInfo("PassWord");
//"Server=myServerName\myInstanceName;Database=myDataBase;User Id=myUsername;Password=myPassword";
string sConnectionString = string.Format("Server={0};Database={2};User Id={3};Password={4}",
sServerName,sSqlInstance,sDataBase,sUserID,sPassWord);
try
{
_cnn = new SqlConnection(sConnectionString);
_cnn.Open();
if (_cnn.State.ToString() != "Open")
{
MessageBox.Show("Application could not connect to server ","Connection Failed ",MessageBoxButton.OK,MessageBoxImage.Error);
}
_cnn.Close();
}
catch (Exception _ex)
{
MessageBox.Show(_ex.ToString());
}
}
【讨论】:
App.config
<add name="databaseName" connectionString="Data Source=localhost; Initial Catalog=ABC_DB; Persist Security Info=True; User ID=sa;Password=1234"/>
Window.xaml.cs
public MainWindow()
{
InitializeComponent();
OpenConnection();
}
public SqlConnection con = new SqlConnection
{
ConnectionString = ConfigurationManager.ConnectionStrings["databaseName"].ConnectionString
};
public void OpenConnection()
{
try
{
con.Open();
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message, "Warning", MessageBoxButton.OK, MessageBoxImage.Error);
/// If you want the program to exit completely
/// Environment.Exit(0);
}
}
另外,你可以这样添加:
public void Whatever()
{
if (con.State == ConnectionState.Open)
{
/// Your code
}
else
{
MessageBox.Show("Could not connect to server", "Warning", MessageBoxButton.OK, MessageBoxImage.Error);
OpenConnection();
}
}
【讨论】: