Go Language
Go Language

Create MySQL Database with Authentication in Golang


Below is a nice snippet for Go Language to create a new MySQL database, and attach a new username and password to access that database.

Set your database root credentials and create a new username, password and database.

1
2
3
4
5
6
7
8
9
10
11
12
// MYSQL CREDS
var dbUser string = "root"
var dbPass string = "password123"
var dbHost string = "localhost"
 
// NEW USER/PASS AND DB NAME
var newUser string = "imnew"
var newPass string = "password123"
var newDbName string = "brandnewdb"
 
// HERE IT GOES!
MakeMySQLDatabase(newUser, newPass, newDbName)

MakeMySQLDatabase Function
creates new database and attaches username/password to database

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// import "database/sql"
 
func MakeMySQLDatabase(username string, password string, dbName string) {
	fmt.Println("Making new MySQL Database with name '" + dbName + "' on server: " + dbHost)
	mysqlString := dbUser + ":" + dbPass + "@tcp(" + dbHost + ":3306)/"
	db, err := sql.Open("mysql", mysqlString)
	if err != nil {
		panic(err)
	}
	defer db.Close()
 
	_, err = db.Exec("CREATE DATABASE " + dbName)
	if err != nil {
		panic(err)
	}
 
	_, err = db.Exec("GRANT ALL PRIVILEGES ON " + dbName+ ".* To '" + username + "'@'%' IDENTIFIED BY '" + password + "'")
	if err != nil {
		panic(err)
	}
}

There you go, you should have a new database and user authentication attached to that new database. If you want to make authentication random, try the RandomString function with your username and password!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var newUser string = RandomString(8)
var newPass string = RandomString(8)
var newDbName string = "brandnewdb"
 
// CREATE THE DATABASE WITH RANDOM USER AUTH!
MakeMySQLDatabase(newUser, newPass, newDbName)
 
 
// Function for creating a random string
// import "math/rand"
// import "time"
 
func RandomString(strlen int) string {
	rand.Seed(time.Now().UTC().UnixNano())
	const chars = "abcdefghijklmnopqrstuvwxyz0123456789"
	result := make([]byte, strlen)
	for i := 0; i < strlen; i++ {
		result[i] = chars[rand.Intn(len(chars))]
	}
	return string(result)
}

View Comments
There are currently no comments.