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?

More than 1 year has passed since last update.

GoでDBに接続する(MySQL)

Last updated at Posted at 2023-03-19

DBに接続します。イメージとしてはPCのローカル環境にDockerのMySQl(MariaDB)を動かしてPCのGoからログインします。Goも並列起動した別イメージのDockerから接続する方が一般的かもしれませんが、開発の初期や検証時などローカル→Docker上のDBに接続したい時があるかと思っているため記載します。

MySQLのDockerFile

docker-compose.yml
services:
  db:
    image: mariadb:10.6.4-focal
    command: '--default-authentication-plugin=mysql_native_password'
    volumes:
      - db_data:/var/lib/mysql
    restart: always
    environment:
      - MYSQL_ROOT_PASSWORD=Dbadmin1
      - MYSQL_USER=user
      - MYSQL_PASSWORD=Dbuser1
      - MYSQL_DATABASE=testdb
    expose:
      - 3306
    ports:
      - 3306:3306
volumes:
  db_data:

起動とシェルの確認

$ docker-compose up -d
$ docker-compose exec -it db /bin/bash
# mysql -u root -p 
MariaDB [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| testdb             |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
5 rows in set (0.001 sec)

GoでDB接続する

main.go
package main

import (
	"database/sql"
	"fmt"

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

func main() {
	testdb, err := sql.Open("mysql", "user:Dbuser1@tcp(127.0.0.1:3306)/testdb")
	if err != nil {
		log.Fatalln(err)
	}
}

Goを動かす

$ go run main.go

想定通り動きました。

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?