Daniel
Daniel

Reputation: 43

How to connect MySQL database to C# WinForm Application?

How do you connect a MySQL database to a C# WinForm Application?

I can establish a connection using a Microsoft SQL Server, but cannot for the life of me figured out how it's done using MySQL.

Upvotes: 1

Views: 21693

Answers (3)

Dev dEV
Dev dEV

Reputation: 11

Step 1 new class conection.cs use this code:

class Conection
    {       
        public static string ConectionString = "server=localhost;database=testDB;uid=root;pwd=abc123;";           
    }

Step 2 Add namespace to the project:

using System.Data.SqlClient;

Step 3 Create a MySQL connection string:

String ConectionString = infor.ConectionString;
SqlConnection conn = new SqlConnection();

Step 4 The following code will insert the data into MySQL table:

private void button1_Click(object sender, EventArgs e)
{
    try
    {
        conn.Open();
        MessageBox.Show ("Connection Open!");
        conn.Close();
    }
    catch (Exception ex)
    {
        MessageBox.Show("Cannot open connection!");
    }
}

NOTE! this connection string is just an example.

Upvotes: 1

hcerim
hcerim

Reputation: 999

Use this code:

string myConnectionString = "server=localhost;database=testDB;uid=root;pwd=abc123;";
private void button1_Click(object sender, EventArgs e)
{
    MySqlConnection cnn = new MySqlConnection(myConnectionString);
    try
    {
        cnn.Open();
        MessageBox.Show ("Connection Open!");
        cnn.Close();
    }
    catch (Exception ex)
    {
        MessageBox.Show("Cannot open connection!");
    }
}

Make sure that you have a proper reference in your code:

using MySql.Data.MySqlClient;

And this connection string is just an example. You have to see what is your connection string ofc. And also search for these kind of questions because I'm sure that there is a bunch of similar or even the same questions on StackOverflow.

Upvotes: 5

O. Jones
O. Jones

Reputation: 108651

You'll need MySQL Connector / Net . Install this, then you'll get a suite of classes like MySqlConnection, MySQLCommand, MySQLDataReader, etc.

These are analogous to SqlConnection and similar classes for MS Sql Server.

https://dev.mysql.com/downloads/connector/net/6.9.html

Upvotes: 1

Related Questions