How can I tell if the connection to the database was successful?

0

I need some help. I started programming in C # now and wanted to do some sort of status for my program. Something like "Connecting to the database: Connected.". I made the connection and my program already puts everything I need in my MySQL database, but my user will not have access to the database when using the program so I wanted to show that everything is working. How can I make a return so that I change the text property of the label? I'm in the right way? I will not put code here because I really do not do the minimum of how to do this. I researched a lot but I did not find it, if someone has already asked a similar question, please send me.

    
asked by anonymous 02.11.2017 / 23:26

2 answers

0
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tutorial.SqlConn;
using MySql.Data.MySqlClient;

namespace ConnectMySQL
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Getting Connection ...");
            MySqlConnection conn = DBUtils.GetDBConnection();

            try
            {
                Console.WriteLine("Openning Connection ...");

                conn.Open();

                Console.WriteLine("Connection successful!");
            }
            catch(Exception e)
            {
                Console.WriteLine("Error: " + e.Message);
            }

            Console.Read();
        }
    }

}
    
02.11.2017 / 23:54
0

You have not specified what you are using to connect to MySQL. Typically, MySql.Data.MySqlClient is used, but it is also possible to do with ODBC driver ( System.Data.Odbc ).

In both cases, the connection class inherits the abstract class DbConnection which has the ConnectionState State { get; } attribute that serves to check the status of the connection.

Example:

MySqlConnection conn = new MySqlConnection({connection string})
//ou 
OdbcConnection conn = new OdbcConnection({connection string});

if (conn.State == ConnectionState.Open)
{
    //Está tudo ok
}
else
{
   //Não está conectado

}
    
02.11.2017 / 23:38