How do I know if the database connection was successful?

Asked

Viewed 1,721 times

1

I need some help. I started programming in c# now and wanted to make a kind of status for my program. Something like "Connection to Database: Connected.". I made the connection and my program already puts everything I need in my database in Mysql, but my user will not have access to the bank when using the program so I wanted a way to show that everything is working. How can I Return so I can change the text property of the label? Am I on the right track? I’m not going to put code here because I really don’t have a clue how to do it. I did a lot of research but I didn’t think, if someone’s ever asked a similar question, please send it to me.

2 answers

1

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

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

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

}

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

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.