Catch problem with Mysql connection c#

Asked

Viewed 201 times

0

Hello I’m a beginner in programming and I’m having trouble connecting Mysql in c#, where the code does not check and goes to catch action. Follows the code:

conexaoDataSet = new DataSet();
            conexao = new MySqlConnection("SERVER=127.0.0.1; DATABASE=tcc; UID=root; PASSWORD=;");
            try
            {
                conexao.Open();
                MySqlCommand verifica = new MySqlCommand("SELECT * FROM CMS_pilots WHERE nome='" + txt_login.Text + "' and senha ='" + txt_senha.Text + "'", conexao);
                bool resultado = verifica.ExecuteReader().HasRows;
                if (resultado == true)
                {
                    conexao.Close();
                    adm f2 = new adm();
                    f2.Show(this);
                    Hide();
                }
                else
                {
                    MessageBox.Show("Login inválido!");
                    conexao.Close();
                }
            }
            //erro acontece a partir de aqui
            catch
            {
                MessageBox.Show("Erro de conexão com o banco de dados");
                conexao.Close();
            }
        }
    }
}
  • 1

    Hello Nayanne, welcome to Sopt. To increase your chances of getting an answer, you’d better include the code instead of the image.

  • Hello, I recommend you read that and that post in the help section on how to format a post here on Sopt.

  • In the block of catch, change the line to catch (Exception ex). And in the message, switch to MessageBox.Show("Erro de conexão, detalhes: " + ex.Message);. This will give you details of what is happening. Edit your question with the error that is returned to you.

1 answer

2

Nayanne, your code is correct, you should not be able to connect to the bank, do the following test: try{ conexao.Open(); } catch{ MessageBox.Show("Não estabeleceu conexão com o banco de dados"); }

You really couldn’t connect? Make sure you have already installed Mysql Connector NET Is your connection string correct? Was the reference made? and was referenced in the correct way?

using MySql.Data.MySqlClient;
using System.Data;

Check in this detailed example that shows from the database modeling, and how to establish the connection to the database.

http://www.macoratti.net/08/08/c_mysql1.htm

Browser other questions tagged

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