Skip to content

Instantly share code, notes, and snippets.

@minhquang4334
Created October 15, 2023 08:56
Show Gist options
  • Save minhquang4334/70399c853d89a1aa3edfcd7c624122d3 to your computer and use it in GitHub Desktop.
Save minhquang4334/70399c853d89a1aa3edfcd7c624122d3 to your computer and use it in GitHub Desktop.
Recreate DB by Go. You can drop currently using database.
package main
import (
"context"
"database/sql"
"fmt"
"time"
_ "github.com/go-sql-driver/mysql"
)
func main() {
mysqlClient, err := sql.Open("mysql", "root:test@tcp(127.0.0.1:3306)/local")
if err != nil {
panic(err)
}
fmt.Println("client created!")
ctx, _ := context.WithTimeout(context.Background(), 15*time.Second)
if err := mysqlClient.PingContext(ctx); err != nil {
panic(err)
}
fmt.Println("Connected to MySQL!")
defer mysqlClient.Close()
// drop database
_, err = mysqlClient.Exec("DROP DATABASE IF EXISTS local")
if err != nil {
panic(err)
}
fmt.Println("Database dropped!")
// create database
_, err = mysqlClient.Exec("CREATE DATABASE local")
if err != nil {
panic(err)
}
fmt.Println("Database created!")
// use database
_, err = mysqlClient.Exec("USE local")
if err != nil {
panic(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment