1
1

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.

sql.Openを別の関数に切り出したら「sql: database is closed」エラー

Last updated at Posted at 2021-12-23

エラー内容

main.go
package main

import (
	"database/sql"
	"log"

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

func main() {
	db := DbConnect() // 別の関数へ切り出し

	err := db.Ping()
	if err != nil {
		log.Fatal(err) // → sql: database is closed
	}
}

func DbConnect() *sql.DB {
	db, err := sql.Open("mysql", "root@tcp(localhost)/dbname")
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	return db
}
zsh
$ go run main.go
2021/12/24 23:59:59 sql: database is closed
exit status 1

対処法

defer db.Close() の位置が悪い

main.go
package main

import (
	"database/sql"
	"log"

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

func main() {
	db := DbConnect()
	defer db.Close() // 移動先

	err := db.Ping()
	if err != nil {
		log.Fatal(err)
	}
}

func DbConnect() *sql.DB {
	db, err := sql.Open("mysql", "root@tcp(localhost)/dbname")
	if err != nil {
		log.Fatal(err)
	}
    // 削除

	return db
}
1
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?