package main
import (
"fmt"
"github.com/go-xorm/xorm"
_ "github.com/mattn/go-sqlite3"
"math/rand"
"strconv"
"time"
)
type User struct {
Id int64
Name string
Age int
Password string `xorm:"varchar(200)"`
Created time. Time `xorm:"created"`
Updated time. Time `xorm:"updated"`
}
func OrmSample ( ) {
engine, err := xorm. NewEngine ( "sqlite3" , "F:\\test\\go_orm.db" )
checkErr ( err)
err = engine. Sync2 ( new ( User) )
checkErr ( err)
fmt. Println ( "=================================insert================================" )
for i:= 0 ; i< 10 ; i++ {
u:= & User{
Name: "user" + strconv. Itoa ( i) ,
Age: rand. Intn ( 60 ) ,
Password: "xxxxxxxxxxxxxx" ,
}
engine. Insert ( u)
}
var user User
user. Name = "user1"
_ , err = engine. Get ( & user)
checkError ( err)
fmt. Println ( "user1 is:" , user)
user = User{ }
_ , err = engine. Where ( "name=?" , "user2" ) . Get ( & user)
checkError ( err)
fmt. Println ( "user2 is:" , user)
var users [ ] * User
err = engine. Asc ( "age" ) . Find ( & users)
checkError ( err)
fmt. Println ( "全部查询:" )
for _ , u:= range users{
fmt. Println ( "user is:" , u. Name)
}
users = [ ] * User{ }
err = engine. Where ( "age > ?" , 30 ) . Find ( & users)
checkError ( err)
fmt. Println ( "30<age多条件查询:" )
for _ , u:= range users{
fmt. Println ( "user is:" , u. Name)
}
users = [ ] * User{ }
err = engine. Where ( "age > ?" , 30 ) . And ( "age < ?" , 50 ) . Find ( & users)
checkError ( err)
fmt. Println ( "30<age<50多条件查询:" )
for _ , u:= range users{
fmt. Println ( "user is:" , u. Name)
}
fmt. Println ( "=================================update================================" )
var u User
u. Name= "user0"
u. Age = 100
affectRow, err:= engine. Where ( "name=?" , "user2" ) . Update ( & user)
checkError ( err)
fmt. Println ( "affected lines are:" , affectRow)
u = User{ }
u. Name = "user2"
u. Age = user. Age
user = User{ }
user. Age = 0
affectRow, err= engine. MustCols ( "age" ) . Update ( & user, & u)
checkError ( err)
fmt. Println ( "=================================delete================================" )
var userList [ ] * User
err = engine. Find ( & userList)
checkError ( err)
for _ , u:= range userList{
engine. Delete ( u)
}
engine. Close ( )
}
func checkError ( err error ) {
if err!= nil {
fmt. Println ( "error is" , err. Error ( ) )
panic ( err)
}
}
func main ( ) {
OrmSample ( )
}