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 connectionimport (
"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