Testing an Entity Framework database connection

前端 未结 6 1662
我在风中等你
我在风中等你 2020-12-08 04:34

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

6条回答
  •  萌比男神i
    2020-12-08 04:44

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

提交回复
热议问题