Accessing MySQL with C #

8

I am creating a simple Form that has 3 TextBoxes and 3 buttons and I want to save the information entered in Textboxes in a table.

I have already created querys all within a class acessoBD , but I can not access MySQL . MySQL is integrated with Visual Studio, there in server explorer I can move to database , create tables, etc. The problem is when it is time to run the program and request access to it via SqlConnection . When I tried with SqlConnection error 40 , now with SqlCeConnection (I saw in a topic that this change could solve the problem) is pointing a new error.

Follow the image

    
asked by anonymous 24.09.2015 / 03:00

1 answer

10

First thing: you are trying to connect to MySQL using SqlCeConnection " which is a class to connect to SQL Server .

To connect to other databases you need to use third-party providers (in the case of MySQL, Oracle). The easiest (and I recommend) way to do this is by using NuGet .

You just have to type in the Package Manager Console the following command:

  

Install-Package MySQL.Data

If you do not know what NuGet is or do not know how to use it, you can take a look at site and this tutorial.

After that, you need to reference namespace MySQL.Data.MySqlClient whenever you want to make a connection.

Here's a small example, with an insert

using System;
using MySql.Data.MySqlClient;

static void Main()
{
    //Aqui você substitui pelos seus dados
    var connString = "Server=localhost;Database=test;Uid=usuario;Pwd=senha"; 
    var connection = new MySqlConnection(connString);
    var command = connection.CreateCommand();

    try
    {
        connection.Open();
        command.CommandText = "INSERT INTO TABELA1 (CAMPO1) VALUES ('VALOR1')";
        command.ExecuteNonQuery();
    }
    finally
    {
        if(connection.State == ConnectionState.Open)
            connection.Close();            
    }
}
    
24.09.2015 / 13:47