How do you Connect MySQL or MariaDB with Go Lang?
Go, also called Golang, is a programming language made by Google. It is similar to the C language but has added features like memory safety, garbage collection, structural typing, and easy handling of multiple tasks at once. Go is known for being simple, efficient, and easy to learn, making it popular for building network services, web applications, and command-line tools.
In this article, we will show you how to connect a Go application to a MySQL or MariaDB database on the AccuWeb.Cloud platform. We will cover the basic steps of setting up an environment, connecting to the database, and running a simple query.
MySQL and MariaDB are widely used open-source databases.
Follow the instructions below to learn how to connect a Go application hosted on the platform to one of these database servers:
Environment Creation
Step 1. Log in to your AccuWeb.Cloud account and click the “New Environment” button at the top left.
Step 2. In the setup wizard, go to the “GO Lang” tab and choose the MySQL or MariaDB database.
Step 3. Adjust the settings (like cloudlets, disk limit, public IPs) as needed, and click “Create.”
Your environment will be ready in a few minutes, and you will get an email with the MySQL admin and connection details.
Connecting to the Database
Step 1. Access your Go server using the Web SSH client.
Step 2. Create a new directory for your project.
In this example, we created a project named accuweb-go-project.
- $ mkdir accuweb-go-project
- $ cd accuweb-go-project
Step 3. Initialize a Go module by running this command:
$ go mod init accuweb-go-project
This will create a go.mod file in your project directory to track dependencies.
Step 4. Prepare a simple Go script to check the connection.
Create a file with a .go extension (e.g., nano dbconnection.go) and write this script to verify the database connection:
package main
import (
"database/sql"
"fmt"
"log"
_ "github.com/go-sql-driver/mysql"
)
func main() {
// Define the MySQL connection string
dsn := "{user}:{password}@tcp({host}:3306)/{db_name}"
// Open a connection to the database
db, err := sql.Open("mysql", dsn)
if err != nil {
log.Fatalf("Error opening database: %v\n", err)
}
defer db.Close()
// Ping the database to test the connection
if err := db.Ping(); err != nil {
log.Fatalf("Error pinging database: %v\n", err)
}
fmt.Println("Successfully connected to the MySQL database!")
}
Step 5. Install the MySQL driver by running this command:
This will download the MySQL driver and update the go.mod and go.sum files.
Step 6. Run the script using the following command:
If everything is set up correctly and the MySQL database is accessible with the provided credentials, you should see:
“Successfully connected to the MySQL database!”
Final Directory Structure
After completing these steps, your project directory should look like this:
accuweb-go-project/
├── go.mod
├── go.sum
└── dbcon.go
Executing Simple Request
Step 1. Create a new file with a .go extension (e.g., insert_user.go) using any text editor, and add the following code:
package main
import (
"database/sql"
"fmt"
"log"
_ "github.com/go-sql-driver/mysql"
)
func main() {
// Define the MySQL connection string
dsn := ""{user}:{password}@tcp({host}:3306)/{db_name}""
// Open a connection to the database
db, err := sql.Open("mysql", dsn)
if err != nil {
log.Fatalf("Error opening database: %v\n", err)
}
defer db.Close()
// Define the user data to insert
username := "Nick"
phone := "1234567890"
// Prepare the insert statement
stmt, err := db.Prepare("INSERT INTO user_details(username, phone) VALUES(?, ?)")
if err != nil {
log.Fatalf("Error preparing statement: %v\n", err)
}
defer stmt.Close()
// Execute the insert statement
res, err := stmt.Exec(username, phone)
if err != nil {
log.Fatalf("Error executing statement: %v\n", err)
}
// Get the last inserted ID
lastInsertId, err := res.LastInsertId()
if err != nil {
log.Fatalf("Error getting last insert ID: %v\n", err)
}
fmt.Printf("Successfully inserted user with ID: %d\n", lastInsertId)
}
Step 2. Run the script using the command:
This Go script will connect to a MySQL database named User_details_db (make sure to use the correct hostname and credentials) and insert a new user into the user_details table. You can see that new user details are added in the user_details table.
Conclusion
Connecting MySQL or MariaDB with Go Lang is easy. First, set up your environment and start a Go module. Then, install the required MySQL driver. Next, create a simple Go script to connect to the database. This includes defining the connection details and performing basic tasks like adding data. Following these steps will help you integrate Go and MySQL or MariaDB smoothly, allowing you to create strong applications.