Golang mysql CREATE DATABASE IF NOT EXISTS

Hello! Golang is studying!

This time we will create a DB and connect to it!

I quickly found a method for connecting to a DB, but I had the impression that many articles created the DB manually. I wanted to operate it automatically from GO instead of executing it directly from Mysql, so I tried to find out how to do it.

Reference article


package main

import (
	"database/sql"

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

// DbConnection grobal
var DbConnection *sql.DB

func checkDb() {
	DbConnection, err := sql.Open("mysql", "root:@tcp(127.0.0.1:3306)/")
	if err != nil {
		panic(err)
	}
	defer DbConnection.Close()

	_, err = DbConnection.Exec("CREATE DATABASE IF NOT EXISTS db_name")
	if err != nil {
		panic(err)
	}
	DbConnection.Close()

	return
}


func main() {
	checkDb()
}

If the package cannot be imported, an error will occur, so please import as appropriate!

Explanation below

I'm connecting to mysql with this code "root:@tcp(127.0.0.1:3306)/"

root username : After that password (this time it is the root user, so there is no password) Protocol after @

After connecting with mysql, check the existence of DB and create it with this code. DbConnection.Exec("CREATE DATABASE IF NOT EXISTS db_name")

Call and execute the function.

func main() {
    checkDb()
}

that's all!

I would like to use ORM for DB operations! If you have any suggestions, please do not hesitate to contact us!

Recommended Posts

Golang mysql CREATE DATABASE IF NOT EXISTS
Create python directory Support if directory exists
Create Python folder Check if it already exists
How to create a new file when the specified file does not exist — write if the file exists