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”
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
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=192.168.0.133;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=192.168.0.133;userid=dfpl;password=dfpl;database=mts"; using var con = new MySqlConnection(cs); con.Open(); Console.WriteLine($"MySQL version : {con.ServerVersion}"); con.Close(); } } }
More Sample Codes are found here
C# MySQL tutorial – programming MySQL in C# (zetcode.com) (zetcode.com/csharp/mysql/)