Access Mysql with C#

Asked

Viewed 22,992 times

9

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

I’ve already created the querys all within a class acessoBD, but I can’t access the Mysql.
The Mysql is integrated with Visual Studio, there in server explorer I can touch the database, create tables, etc. The problem is when to run the program and ask for access to it via SqlConnection. When I tried to SqlConnection kind of error 40, now with SqlCeConnection (vi in a topic that this change could solve the problem) is pointing out a new error.

Follow the imageerrosql

  • Daniel, in your image, at no time are you accessing the bank. And more importantly, you’re trying to access a Mysql database using the Sqlserver providader, so it won’t even rs. You must install the mysql package. Here are some links that can help you: http://www.codeproject.com/Tips/423233/How-to-Connect-to-MySQL-Using-Csharp http://www.macoratti.net/08/c_mysql1.htm

1 answer

12


First thing: you’re 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 providers third party (in the case of Mysql, Oracle). The easiest way (and I recommend) to do this is by using Nuget.

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

Install-Package Mysql.Data

If you don’t know what Nuget is or don’t know how to use it, you can check out website and in that tutorial.

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

Here is a small example, with an operation of 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();            
    }
}

Browser other questions tagged

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