ASP.NET CoreでMySQLを使ってみる -データ取得

はじめに

今回は、ASP.NET CoreでMySQLからのデータ取得をやってみます。

サンプルデータ入力

MySQLにサンプルデータをINSERTします。
今回はGUIで手っ取り早くやりました。
DBeaverというアプリケーションを使うと楽です。
dbeaver.io
テーブルの定義はこんな感じで。
f:id:sublimer:20191214200316p:plain
データもこんな感じで入れておきます。
f:id:sublimer:20191214200505p:plain

実装

前回のコードをこんな感じに変更します。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using MySql.Data.MySqlClient;

namespace aspdotnet_mysql_sample.Pages
{
    public class IndexModel : PageModel
    {
        private readonly String DBName = "aspdotnet";
        private readonly String DBHost = "127.0.0.1";
        private readonly String DBPort = "43306";
        private readonly String DBUser = "root";
        private readonly String DBPass = "mysql";
        private readonly String TableName = "data";
        private readonly ILogger<IndexModel> _logger;
        private MySqlConnection connection;

        public IndexModel(ILogger<IndexModel> logger)
        {
            _logger = logger;
            String ConnectionString = $"server={DBHost};port={DBPort};uid={DBUser};pwd={DBPass};database={DBName}";
            try
            {
                connection = new MySqlConnection();
                connection.ConnectionString = ConnectionString;
                connection.Open();
                Console.WriteLine(connection.ServerVersion);
            }
            catch (MySqlException e)
            {
                Console.WriteLine(e.Message);
            }
        }
        ~IndexModel()
        {
            connection.Close();
            Console.WriteLine("Connection Closed");
        }

        public void OnGet()
        {
            String sql = $"SELECT * FROM {TableName}";
            MySqlCommand command = new MySqlCommand(sql, connection);
            MySqlDataReader dataReader = command.ExecuteReader();
            while (dataReader.Read())
            {
                Console.WriteLine($"{dataReader[0]} -- {dataReader[1]}");
            }
            dataReader.Close();
        }
    }
}

動作確認

前回同様にブラウザでアクセスすると、コンソールにデータベースに記録した内容が出力されます。

おわりに

データの取得ができたので、次回は結果をWebページに出力するようにしてみたいと思います。