官方 sql
func main() {
type Userinfo struct {
Id uint
Username string
Department string
Created string
}
db, err := sql.Open("mysql","root:root@tcp(localhost:3306)/gorm")
if err != nil {
log.Fatal(err.Error())
}
defer db.Close()
//准备语句,避免多次重复执行
stmt,err := db.Prepare("INSERT userinfo SET username=?,department=?,created = ?")
if err != nil {
log.Fatal(err.Error())
}
res,err := stmt.Exec("lisi","ad",time.Time{})
if err != nil {
log.Fatal(err.Error())
}
log.Println(res )
rows,err := db.Query("SELECT * FROM userinfo")
if err != nil {
log.Fatal(err.Error())
}
var userinfo Userinfo
for rows.Next() {
rows.Scan(&userinfo)
}
}
gorp
type Product struct {
Id int64 `db:"product_id"`
PName string `db:"pname"`
Price int `db:"price"`
}
func main() {
db, err := sql.Open("mysql", "root:root@tcp(localhost:3306)/gorm")
if err != nil {
log.Fatal(err.Error())
}
defer db.Close()
//官方sql -> gorp
dbmap := &gorp.DbMap{Db:db,Dialect:gorp.MySQLDialect{"InnnoDB","UTF8"}}
dbmap.CreateTablesIfNotExists()
//日志处理
dbmap.TraceOn("[gorp]", log.New(os.Stdout, "app", log.Lmicroseconds))
product := Product{11101,"taozi",2000}
dbmap.Insert(&product)
dbmap.Delete(&product)
var products []Product
_, err = dbmap.Select(&products, "select * from product")
var prod Product
err = dbmap.SelectOne(&prod, "select * from product where product_id=?", 3)
fmt.Println("product:", prod)
//对原生的支持
result, err := dbmap.Exec("delete from seller where seller_id=?", 2)
log.Println(result.RowsAffected())
}
func InsertTrans(dbmap *gorp.DbMap, product *Product) error {
trans, err := dbmap.Begin()
if err != nil {
return err
}
trans.Insert(product)
return trans.Commit() //if commint is sucdessful ,a nil error is returned
}
gorm
有疑问加站长微信联系(非本文作者)