1
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?

アドベントカレンダー7日目です。
goでmysqlを扱います。

docker-composeにmysql関連の記述を追加します。

version: '3'
services:
  golang:
    build: .
    tty: true
    volumes:
      - ./:/app/
    ports:
      - "1323:1323"
  mysql:
    image: mariadb # mysqlと言いつつmariadb使っています
    environment:
      MYSQL_ROOT_PASSWORD: root
      MYSQL_DATABASE: golang
      MYSQL_USER: golang
      MYSQL_PASSWORD: golang
    ports:
      - "3310:3306"
    volumes:
      - ./mysql:/var/lib/mysql

コンテナを起動します。

docker-compose up -d

ローカルから接続してみます。

$ mysql -ugolang -pgolang -P 3310
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 10
Server version: 10.9.3-MariaDB-1:10.9.3+maria~ubu2204 mariadb.org binary distribution

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]>

コンテナが起動していることの確認ができました。
適当にusersテーブルを作成しておきます。

MariaDB [(none)]> use golang;
Database changed
MariaDB [golang]> CREATE TABLE users (
    ->     id INT AUTO_INCREMENT PRIMARY KEY,
    ->     username VARCHAR(50) NOT NULL,
    ->     password VARCHAR(50) NOT NULL,
    ->     email VARCHAR(100),
    ->     created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    -> );
Query OK, 0 rows affected (0.042 sec)

MariaDB [golang]>

goからアクセスする

ライブラリをインストールします。

docker-compose exec golang go get github.com/go-sql-driver/mysql
package main

import (
	"database/sql"
	"fmt"

	_ "github.com/go-sql-driver/mysql"
)

func main() {
	// データベースの接続情報(ハードコーディング勘弁)
	db, err := sql.Open("mysql", "golang:golang@tcp(mysql:3306)/golang")
	if err != nil {
		fmt.Println("Failed to connect to the database:", err)
		return
	}
	defer db.Close()

    // データの作成
	_, err = db.Exec("insert into users (username, email, password, created_at) values (?, ?, ?, now())", "test", "test", "test")
	if err != nil {
		fmt.Println("Failed to insert data:", err)
		return
	}

	// データの取得
	rows, err := db.Query("select * from users")
	if err != nil {
		fmt.Println("Failed to select data:", err)
		return
	}
	defer rows.Close()
	for rows.Next() {
		var id int
		var username string
		var email string
		var password string
		var createdAt string
		err := rows.Scan(&id, &username, &email, &password, &createdAt)
		if err != nil {
			fmt.Println("Failed to scan data:", err)
			return
		}
		fmt.Println(id, username, email, password, createdAt)
	}
}

所感

結構標準ライブラリだけでsqlを扱うのは大変な気がします。
gormなり、sqlboilerなどの使用を検討したいところです。

1
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
1
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?