Created
October 15, 2023 08:56
-
-
Save minhquang4334/70399c853d89a1aa3edfcd7c624122d3 to your computer and use it in GitHub Desktop.
Recreate DB by Go. You can drop currently using database.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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