Skip to content

Instantly share code, notes, and snippets.

@kgoralski kgoralski/basic_dao.go Secret
Created Nov 14, 2016

Embed
What would you like to do?
basic_dao.go
package main
import (
_ "github.com/go-sql-driver/mysql" // db driver registration
"github.com/jmoiron/sqlx"
"log"
)
const (
sqlConnection = "admin:Admin.123@tcp(localhost:3306)/people_db?charset=utf8"
mysql = "mysql"
)
type Person struct {
ID int `db:"id"`
Name string `db:"name"`
}
type PeopleAPI struct {
db *sqlx.DB
}
func NewPeopleAPI() (*PeopleAPI, error) {
db, err := sqlx.Connect(mysql, sqlConnection)
if err != nil {
return nil, err
}
return &PeopleAPI{db: db}, nil
}
func getPeopleFromDB(p *PeopleAPI) []Person {
var people []Person
if err := p.db.Select(&people, "SELECT * FROM people"); err != nil {
log.Print(err)
}
return people
}
func createPersonInDB(p *PeopleAPI, name string) int {
result, err := p.db.Exec("INSERT into people (name) VALUES (?)", name)
if err != nil {
log.Print(err)
}
lastID, err := result.LastInsertId()
if err != nil {
log.Print(err)
}
return int(lastID)
}
func main() {
db, err := NewPeopleAPI()
if err != nil {
log.Fatal(err)
}
createPersonInDB(db, "Heniek")
people := getPeopleFromDB(db)
log.Print(people)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.