I have an app that connects to a MYSQL database through the entity framework. It works 100% perfectly, but I would like to add a small piece of code that will test the conne
I am using the following code for MS SQL connection. Maybe, it will be useful for MySQL too. You don’t even need to use an EF or EF Core.
public bool IsDbConnectionOK()
{
SqlConnectionStringBuilder conStr = new SqlConnectionStringBuilder
{
DataSource = ButtonServerName.Text, // <-- My Form Elements
InitialCatalog = ButtonDBName.Text, // <-- My Form Elements
UserID = EditUserName.Text, // <-- My Form Elements
Password = EditPassword.Text, // <-- My Form Elements
IntegratedSecurity = false,
ConnectTimeout = 30
};
string connectionstring = conStr.ToString();
try
{
using (System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(connectionstring))
{
connection.Open();
return true;
}
}
catch (System.Data.SqlClient.SqlException ex)
{
MessageBox.Show(ex.Message + Environment.NewLine +
"Error line: " + ex.LineNumber + Environment.NewLine +
"Procedure name: " + ex.Procedure);
return false;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return false;
}
}