GO Connect to Database
Table of Contents:
- [Start to Connect Database]
- [Create Return Function]
- [Create CRUD]
- [Transaction]
Start to Connect Database
package main
import {
"database/sql"
// import driver that use in /sql package
_ "github.com/denisenkom/go-mssqldb"
}
func main() {
db, err := sql.Open("sqlserver", "sqlserver://<user>:<password>@<host>:1443/<database>")
if err != nil {
panic(err)
}
err = db.Ping()
if err != nil {
panic(err)
}
query := "select id, name from cover"
row, err := db.Query(query)
if err != nil {
panic(err)
}
defer rows.Close()
for rows.Next() {
id := 0
name := ""
err = rows.Scan(&id, &name)
if err := nil {
panic(err)
}
println(id, name)
}
}
Create Struct for receive data
covers := []Cover{}
for rows.Next() {
cover := Cover{}
err = rows.Scan(&cover.Id, &cover.Name)
if err != nil {
panic(err)
}
covers = append(covers, cover)
}
fmt.Printf("%#v", covers)
Create Return Function
var db *sql.DB
func main() {
var err error
db, err = sql.Open("sqlserver", "sqlserver://<user>:<password>@<host>:1443/<database>")
if err != nil {
panic(err)
}
covers, err := GetCovers()
if err != nil {
fmt.Println(err)
return
}
for _, cover := range covers {
fmt.Println(cover)
}
}
func GetCovers() ([]Cover, error) {
err = db.Ping()
if err != nil {
return nil, err
}
query := "select id, name from cover"
row, err := db.Query(query)
if err != nil {
return nil, err
}
defer rows.Close()
covers := []Cover{}
for rows.Next() {
cover := Cover{}
err = rows.Scan(&cover.Id, &cover.Name)
if err != nil {
return nil, err
}
covers = append(covers, cover)
}
return covers, nil
}
Note: \ You should not create error handler process in your err.
Create CRUD
Read
func GetCover(id int) (*Cover, error) {
err := db.Ping()
if err != nil {
return nil, err
}
// Use @id for SQL Server
query := "select id, name from cover where id=@id"
row := db.QueryRow(query, sql.Named("id", id))
cover := Cover{}
err = row.Scan(&cover.Id, &cover.Name)
if err != nil {
return nil, err
}
return &cover, nil
}
Note: \ If you use MySQL, the above query row syntax will change to
Create
func AddCover(cover Cover) error {
query := "insert into cover (id, name) values (?, ?)"
result, err := db.Exec(query, cover.Id, cover.Name)
if err != nil {
return err
}
affected, err := result.RowAffected()
if err != nil {
return err
}
if affected <= 0 {
return errors.New("cannot insert to cover table")
}
return nil
}
Update
func UpdateCover(cover Cover) error {
query := "update cover set name=? where id=?"
result, err := db.Exec(query, cover.Name, cover.Id)
if err != nil {
return err
}
affected, err := result.RowAffected()
if err != nil {
return err
}
if affected <= 0 {
return errors.New("cannot update to cover table")
}
return nil
}
Delete
func DeleteCover(id int) error {
query := "delete from cover where id=?"
result, err := db.Exec(query, id)
if err != nil {
return err
}
affected, err := result.RowAffected()
if err != nil {
return err
}
if affected <= 0 {
return errors.New("cannot delete to cover table")
}
return nil
}
SQLX
package main
import {
_ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
}
var db *sqlx.DB
func main() {
var err error
db, err = sqlx.Open("mysql", "root:<password>@tcp(<host>)/<database>")
if err != {
panic(err)
}
}
func GetCoversX() ([]Cover, error) {
query := "select id, name from cover"
covers := []Cover{}
err = db.Select(&covers, query)
if err != nil {
return nil, err
}
return covers, nil
}
Change Read
func GetCoverX(id int) (*Cover, error) {
query := "select id, name from cover where id=?"
cover := Cover{}
err = db.Get(&cover, query, id)
if err != nil {
return nil, err
}
return &cover, nil
}