0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

.NETのお勉強3_mysqlコンテナと連携

Last updated at Posted at 2025-01-28

概要

AmazonLinux2023インスタンス上にコンテナで.NETを利用したサーバをたてる
そのお勉強メモ3

mysqlコンテナと連携する

連携の前にmysqlコンテナ単体たてる

最低限がこんな感じ
データの永続化のためvolumesで外にも出す

docker-compose.mysql.yml
services:
  mysql:
    image: mysql:8.0
    environment:
      MYSQL_ROOT_PASSWORD: admin
    ports:
      - "3306:3306"
    volumes:
      - ./mysql:/var/lib/mysql

テーブル作ってテストデータ入れとく

mysqlコンテナ内からcliでmysqlに入ってコマンド実行

CREATE TABLE example (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255) NOT NULL);
INSERT INTO example (name) VALUES ('Tanaka'),('Sato'),('Yamada');

ソース

src/Controller/MysqlController.cs
using Microsoft.AspNetCore.Mvc;
using MySql.Data.MySqlClient;

[ApiController]
[Route("[controller]")]
public class MysqlController : ControllerBase
{
    [HttpGet("{id}")]
    public IActionResult Get(int id)
    {
        string connectionString = "Server=mysql;Port=3306;Database=cs_test;User=user;Password=password;";
        var connection = new MySqlConnection(connectionString);
        connection.Open();

        string query = "SELECT name FROM example WHERE id = @id";
        var command = new MySqlCommand(query, connection);
        command.Parameters.AddWithValue("@id", id);
        var reader = command.ExecuteReader();

        string name = string.Empty;
        if (reader.Read()) {
            name = reader["name"].ToString();
        } else {
            return NotFound($"Not found! ID={id}");
        }

        return Content(name, "text/plain");
    }
}
src/MyServerApp.csproj
<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>net9.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="MySql.Data" Version="8.1.0" />
  </ItemGroup>
</Project>
docker-compose.hotload.yml
services:
  build:
    image: builder
    build:
      context: .
      dockerfile: Dockerfile.build
    volumes:
      - ./src:/src
    ports:
      - "80:8080"
    command: dotnet watch run --urls=http://0.0.0.0:8080
  mysql:
    image: mysql:8.0
    environment:
      MYSQL_ROOT_PASSWORD: root_password
      MYSQL_USER: user
      MYSQL_PASSWORD: password
      MYSQL_DATABASE: cs_test
    ports:
      - "3306:3306"
    volumes:
      - ./mysql:/var/lib/mysql

実行テスト

xx.xx.xx.xx/mysql/1アクセスで、Tanaka
xx.xx.xx.xx/mysql/2アクセスで、Sato
xx.xx.xx.xx/mysql/3アクセスで、Yamada
xx.xx.xx.xx/mysql/4アクセスで、Not found! ID=4
と画面表示されればok

その他メモ

IActionResult型

HTTP レスポンスを返すための抽象型
return Ok(object) => 200レスポンス
return NotFound(string) => 404レスポンス
return BadRequest(string) => 400レスポンス
等、柔軟に色々なレスポンスに対応している

ルート定義

例えば
[HttpGet("{id}")]ならxx.xx.xx.xx/mysql/{id}のGET通信
[HttpGet("method_name")]ならxx.xx.xx.xx/mysql/method_nameのGET通信
[HttpPost]ならxx.xx.xx.xx/mysqlのPOST通信

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?