有些情况下需要使用原生SQL方式来访问数据库。例如需要构造的SQL语句比较复杂,使用Model不足以表达如此复杂的SQL语句。
还有一种情况就是SQL非常简单,不需要先定义struct, 然后在使用Model进行数据库操作。
func demoSqlExec() {
//插入记录
res, _ := worm.SQL("insert into users(name, age) values(?,?)", "name1", 1).Exec()
id, _ := res.LastInsertId()
log.Println(id)
//更新记录
res, _ = worm.SQL("update users set name=? where id=?", "name2", id).Exec()
affected, _ := res.RowsAffected()
log.Println(affected)
//删除记录
res, _ = worm.SQL("delete from users where id=?", id).Exec()
affected, _ = res.RowsAffected()
log.Println(affected)
}
说明:
func demoSQLGet() {
//查询单条记录到model对象
var user User
has, err := worm.SQL("select * from users where id=?", 1).GetModel(&user)
log.Println(user)
//查询单条记录
var name string; var age int64
has, err = worm.SQL("select name,age from users where id=?", 1).Get(&name, &age)
log.Println(name, age)
//单条记录的单个字段的查询:
strval, err := worm.SQL("select name from users where id=?", 1).GetString()
log.Println(strval)
//单条记录的单个字段的查询:
intval, err := worm.SQL("select age from users where id=?", 1).GetInt()
log.Println(intval)
}
GetRow查询一条记录,并返回map[string]string类型的结果。
func demoSQLGetRow() {
val, err := worm.SQL("select * from users where id=?", 1).GetRow()
if err != nil{
log.Println(err)
return
}
log.Println(val)
}
func demoSQLFind() {
//查询多条记录到model数组
var users []User
worm.SQL( "select * from users where id>?", 1).FindModel(&users)
log.Println(users)
//查询多条记录的单个字段到[]string:
arrstr, err := worm.SQL( "select name from users where id>?", 1).FindString()
log.Println(arrstr)
//查询多条记录的单个字段到[]int64:
arrint, err := worm.SQL( "select age from users where id>?", 1).FindInt()
log.Println(arrint)
}
func demoSQLRows() {
rows, err := worm.SQL("select * from users where id>?", 0).ModelRows()
if err != nil{
log.Println(err)
return
}
defer rows.Close()
for rows.Next(){
var user User
err = rows.Scan(&user)
if err != nil{
log.Println(err)
}
log.Println(user)
}
}
您也可以使用StringRows来获取map[string]string类型的结果:
func demoSQLRows2() {
rows, err := worm.SQL("select * from users where id>?", 0).StringRows()
if err != nil{
log.Println(err)
return
}
defer rows.Close()
for rows.Next(){
data := make(worm.StringRow)
err := rows.Scan(&data)
if err != nil{
log.Println(err)
}
log.Println(data)
}
}