Download Navicat for MySQL

.NET is great and provides a lot of tools for working with databases and data sources. Sometimes, though, data sources may not be inherently supported. In cases such as MySQL, you may not see the MySQL connection option when you create a binding source or data source for your project.

So what do you do?

First, download some tools, including MySQL connector:

  • Dev.mysql.com/downloads/f…
  • Dev.mysql.com/downloads/f…
  • Dev.mysql.com/downloads/c…

After downloading the installation files, install them one by one. If you are using Visual Studio, be sure to turn it off before installing.

After installing the tools for MySQL, open Visual Studio and create the Windows Forms project.

Select the BindingSource control from the toolbox, and then double-click it. In the Bind Source properties window, select the **DataSource ** property, and then select Add Project DataSource. This opens the Data Source Configuration Wizard.

Select Database, and then select next.

Select the Dataset, and then select next.

Select the New Connection button.

Select the Change button.

Notice that the MySQL database now appears in the list, as shown in Figure 1.

Figure 1 –

Changing the data source

Select MySQL Database from the list, then click OK, and the Add Connection dialog will look like Figure 2.

Figure 2 –

Adding a connection

Enter the server name, username, and password as shown in Figure 2, and click OK.

Select the database objects you want, as shown in Figure 3.

Figure 3 –

Database object

Click Finish.

Now you can connect to the MySQL database and use it.

What if I don’t want to use Bindingsource or even design views? What if I just want to use code?

Let’s see.

To import the Data functionality, you need to import the MySQL namespace and the system.data namespace as follows:

using MySql.Data.MySqlClient;
using System.Data;
Copy the code

You just use the using statement in C#. You now have access to all the functionality of the MySQLClient namespace.

MySqlConnectionParameters connectionParameters = new MySqlConnectionParameters("Server", "Database", "User", "Password"); string conStr = "server=ServerName; port=PortNumber; database=DatabaseName; uid=Username; password=Password; TreatTinyAsBoolean=false";Copy the code

To get data from the MySQL stored procedure, use the following code:

   MySqlConnection con = new MySqlConnection(conStr);
 
   MySqlDataAdapter adapter = new MySqlDataAdapter();
   MySqlCommand cmd;
 
   cmd = new MySqlCommand("CALL StoredProcedureName(@Parameter)", con);
 
   cmd.Parameters.AddWithValue("@Parameter", Parameter);
   cmd.Parameters.AddWithValue("@ToDate", ToDate);
 
   adapter.SelectCommand = cmd;
   DataSet ds = new DataSet();
 
   adapter.Fill(ds);
Copy the code

conclusion

As you can see, use. NET is very easy to connect to the MySQL database. Have fun coding!