c# - How to correctly check database connection with mysql in a .NET application? -


First of all I would like to be precise that I am searching on the internet to solve my problem and I think all the classic

  if (connection.open) is true;  

The solution which does not work for my needs in my case.

I am working on an application. Before I run, I have to check the connection in the MySQL database, if the connection is not made, the user has been opened to open a new window for connection settings (username, server address, password ...) . In this window I have a Connection Connection button, to see if the connection is established, this is the code of button_click event:

  Private Zero Button_Click_1 (Object Sender, RoutedEventArgs e) { ApplicationSettings applicationSettings = New Application Settings (); ApplicationSettings.ServerDatabase = tbdbName.Text; ApplicationSettings.ServerIp = tbServer.Text; ApplicationSettings.ServerUserName = tbUsername.Text; //applicationSettings.ServerPassword = pbPassword.SecurePassword; ApplicationSettings.MakeConnectionString (); MySqlConnection connection = New MySqlConnection (applicationSettings.ConnectionString); Try {connection.Open (); MessageBox.Show (this, "Connection String:" + Application Settings. Connection String + "Connection OK!", "Ok!", Message Box Button. OK, Message Box Image. } Hold (exception EE) {message box. Show (this, "Connection String:" + Application Settings. Connection String + "Error:" + E. Message, "Connection ERROOOOR", MessageBoxButton.OK, MessageBoxImage.Error); } Finally {if (connection.State == ConnectionState.Open) connection.Close (); }}  

If I enter the only server address "applicationSettings.ServerIp" and click on the Test Connection button, the message box is displayed correctly and the connection string is:

server = 127.0.0.1; Database =; Password =;

I think this is quite logical, but I have to check that the connection is established in the database, even if I fill the login text box with any random value, the connection has been established.

Question : If I have a connection with the database, how can I test it?

Connect to the database, SELECT 1 to & quot; Known Tablet & gt; and make sure that you successfully get '1' back, it confirms that you have

  1. connected to the physical server (no network problem)
  2. Certified with database server (the database is running and you have the correct credentials)
  3. Connect to the correct database

Comments

Popular posts from this blog

sqlite3 - UPDATE a table from the SELECT of another one -

c# - Showing a SelectedItem's Property -

javascript - Render HTML after each iteration in loop -