1.连接数据库
func Connect()(* xorm.Engine) {
str := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", host, port, user, password, dbName)
engine,err := xorm.NewEngine("postgres",str)
if err != nil {
log.Fatal(err)
return nil
}
err = engine.Ping()
if err != nil {
log.Fatal(err)
return nil
}
engine.Logger().SetLevel(core.LOG_DEBUG)
f,err := os.Create("sql.log")
if err != nil {
println(err.Error())
return nil
}
engine.SetLogger(xorm.NewSimpleLogger(f))
fmt.Println("postgresql access succ")
err = engine.Sync2(new(models.Student))
engine.ShowSQL()
if err != nil {
log.Fatal(err)
}
return engine
}
2.最简洁的增删改查
/*
postgresql 数据库的增删改查
增engine.Insert(Student)
删engine.Exec(sql,...)
改engine.Exec(sql,...)
查engine.Sql(sql,...)
*/
tt := Connect()
增
stu := new(models.Student)
stu.Name = c.GetString("name")
stu.Num = c.GetString("num")
stu.CreateTime = time.Now().Format("2006-01-02 15:04:05")
affect,err := tt.Insert(*stu)
删
sql = "delete from student where num = ?"
res,err := tt.Exec(sql,num)
改
sql := "update student set name = ?,update_time = ? where num = ?"
res,err := tt.Exec(sql,name,uptime,num)
查
sql := "select num,name from student where num = ?"
res,err := tt.SQL(sql,num).QueryInterface()
有疑问加站长微信联系(非本文作者)