C# Code to connect to MYSQL on Raspberry Pi

This is a follow up post to this last one where we installed mysql on raspberry pi and added a remote user to it. If you haven’t done it, then please go here and do that first on raspberry pi

Add the MySQL Connector to Visual Studio

In order to use MySQL related code in your program, you need to add the default mysql connector to your project. Which is using MySql.Data.MySqlClient;

To do this, just right click your project and click on “Manage nuGET Packages”

manage nuget packages
manage nuget packages

Click on the Manage nuget packages link as shown in the yellow box in above Image. This will open the nuget package manager in visual studio. Here, simply search for Mysql and you’ll get the first result as the MySQL.Data by Oracle. That is the one we need to install

See the Image below

mysql on raspberry pi

Click on the MySQl.Data and install that package, it should take about 2-5 minutes. Once done, you can run the next program to check the connection between C# code and mysql running on raspberry pi

.net code to connect to mysql on raspberry pi

Once everything is in place, just open your visual studio and create a console application. You need to use below code in console application to test your connection. Make sure to use the IP address, user name and password according to your particular instance. Just make sure to change this line in the code as per your raspberry pi address and userid and password of database and also the database name.

string cs = @”server=;userid=YOURUSERID;password=YOURPASSWORD;database=YOURDBNAME”;

Run the console application. If it shows the version of the mariadb on console, it means your connection is working

using System;
using MySql.Data.MySqlClient;

namespace ConsoleApp_testMariadb
    class Program
        static void Main(string[] args)
            string cs = @"server=;userid=dfpl;password=dfpl;database=mts";
            using var con = new MySqlConnection(cs);
            Console.WriteLine($"MySQL version : {con.ServerVersion}");

More Sample Codes are found here

C# MySQL tutorial – programming MySQL in C# (zetcode.com) (zetcode.com/csharp/mysql/)

Tutorials and Posts you may be interested in...

How to use bluetooth with 8051

This Project is Suitable for Everyone Including student and Professional Bluetooth-based relay control using an 8051-based microcontroller involves using Bluetooth communication to remotely control the switching of a relay. Here’s

Read More »

How to use Raspberry Pi Pico W with Optocoupler

Optocouplers, also known as opto-isolators, are electronic components that provide electrical isolation between two circuits by using light to transfer signals. Optocouplers are commonly used to protect sensitive electronic devices

Read More »