【问题标题】:Checked If there is Connection to SQL Server or not in WPF检查 WPF 中是否存在与 SQL Server 的连接
【发布时间】:2014-03-30 21:19:36
【问题描述】:

我的 WPF 应用程序通过App.config 中的连接字符串连接到 SQL Server 数据库,它可以在本地网络上运行。

我有一个登录屏幕“4 位密码登录”,在输入第四位数字后,我检查了“照常”是否正确。

我的问题是如何检查客户端机器是否连接到服务器?如果不是,我想显示消息。

我不知道我应该从哪里开始:(

希望这一点清楚。 谢谢

【问题讨论】:

    标签: c# wpf sql-server-2008


    【解决方案1】:

    您可以简单地检查执行检查客户端是否可以打开连接。

    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();
            }
        }
    }
    

    【讨论】:

    • 感谢@Oren 抽出宝贵时间,这就是我正在寻找的 :)
    • 很抱歉复活了这个,但是如何初始化这个方法呢? IsServerConnected(); 不起作用。
    • @Adephx 你必须比“不起作用”更具体一点。你有一个要复制这个方法的类吗?
    【解决方案2】:

    试试这个

    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());
            }
    
        }
    

    【讨论】:

      【解决方案3】:

      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();
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-09-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-18
        • 2012-07-29
        • 2020-08-16
        相关资源
        最近更新 更多