⌘BABAKOV.NET Let's code!
100% [dark] [ru]

Working with MySQL Database from .NET Core C#

In this publication, we will consider how to connect to the MySQL database from a .Net Core application.

1. If you have not installed .Net Core yet, install it: .NET Core.

2. Then create a new .NET Core project.

mkdir MySqlCoreSample
cd MySqlCoreSample
dotnet new


After executing these commands in the MySqlCoreSample folder, 2 files will appear: «Program.cs», «project.json».
This is the simplest template for a .NET Core application.
We will make changes to these files using Visual Studio Code.

3. Using the NuGet extension, add the "MySql.Data.7.0.6-ir31" package to our project
And add a dependency to the «project.json» file.
After changes, the «project.json» file should look like this:

{
  "version": "1.0.0-*",
  "buildOptions": {
    "debugType": "portable",
    "emitEntryPoint": true
  },
  "dependencies": {
    "MySql.Data": "7.0.6-ir31"
    },
  "frameworks": {
    "netcoreapp1.0": {
      "dependencies": {
        "Microsoft.NETCore.App": {
          "type": "platform",
          "version": "1.0.1"
        }
      },
      "imports": "dnxcore50"
    }
  }
}



4. Now let's move away from the project and create and fill our test MySQL database with test data.

CREATE DATABASE  IF NOT EXISTS `test` /*!40100 DEFAULT CHARACTER SET utf8 */;

USE `test`;

DROP TABLE IF EXISTS `cat`;

CREATE TABLE `cat` (
  `idcat` int(11) NOT NULL,
  `name` varchar(45) DEFAULT NULL,
  `dt` datetime DEFAULT NULL,
  PRIMARY KEY (`idcat`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

LOCK TABLES `cat` WRITE;

INSERT INTO `cat` VALUES (1,\'Колбаса\',\'2016-10-28 22:10:30\'),(2,\'Сыр\',\'2016-10-28 22:10:47\'),(3,\'Хлеб\',\'2016-10-28 22:10:58\');

UNLOCK TABLES;


The database consists of one catalog table with three products, which is enough for our experiment.

5. The last step, we return to our project and change the «Program.cs» file as follows:

using System;
using MySql.Data.MySqlClient;

namespace ConsoleApplication
{
    public class Program
    {
        public static void Main(string[] args)
        {
            MySqlConnection connection = new MySqlConnection
            {
                //Строка подключения, у вас может отличаться.
                ConnectionString = "server=localhost;user id=root;password=240580;persistsecurityinfo=True;port=3306;database=test;CharSet=utf8"
            };
 
            MySqlCommand command = new MySqlCommand("SELECT * FROM test.cat;", connection);
            
            
            connection.Open();
            using (MySqlDataReader reader =  command.ExecuteReader())
            {
                System.Console.WriteLine("Идентификатор\\t\\tНаименование\\t\\tДата изменения");
                //Перебираем все полученные данные в цикле.
                while (reader.Read())
                {
                string row = $"{reader["idcat"]}\\t\\t{reader["name"]}\\t\\t{reader["dt"]}";
                System.Console.WriteLine(row);
                }
            }
 
            connection.Close();
            Console.WriteLine("Нажми кнопку чтобы выйти!");
            System.Console.ReadKey();   
            Console.WriteLine("Покедова!");
        }
    }
}



6. Restore and run the application from the console.

dotnet restore
dotnet run



We should see this:
 

That's it!

Comments (0)

No comments yet.

Leave a comment
Comment
Images (up to 5 MB)
Your comment will appear after moderation.