How to create a connection to Database using go lang | by Achmad Fatoni | Jan, 2024

How to create a connection to Database using go lang | by Achmad Fatoni | Jan, 2024

In the steps above we have created a database and table that we will use to connect using Go Lang. The next step is to create a service and configure it to connect to the database that was created previously. Here are the steps:

1. First initiate our project using the following command:

go mod init [nama project]

# example
go mod init test-connection-db

2. Because here I am using MySQL as the database, here we need to add the MySQL driver package.

go get github.com/go-sql-driver/mysql

3. Next, we setup the database connection by creating a new file called connection/database.go. Paste the following code :

package connection

import (
"database/sql"
"time"

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

func GetConnection() *sql.DB {
// username = root
// password = admin
// host = 127.0.0.1
// db name =...


Source link

About hosting

Check Also

Don’t Use Usual Web-Hosting for Your Website. Here is Why

Don’t Use Usual Web-Hosting for Your Website. Here is Why

The first thing you usually do when you want to start a website is buying …

Leave a Reply

Your email address will not be published. Required fields are marked *