qbs使用原生 sql 语句的例子

ORMkevin1889 次浏览
package main

import (
	"fmt"
	_ "github.com/coocood/mysql"
	"github.com/coocood/qbs"
	"time"
)

type User struct {
	Id   int64
	Name string
}

func RegisterDb() {
	qbs.Register("mysql", "root:root@tcp(localhost:8889)/qbs_test?charset=utf8", "qbs_test", qbs.NewMysql())
}

func CreateUserTable() error {
	migration, err := qbs.GetMigration()
	if err != nil {
		return err
	}
	defer migration.Close()
	return migration.CreateTableIfNotExists(new(User))
}

func main() {
	RegisterDb()
	CreateUserTable()

	q, err := qbs.GetQbs()
	if err != nil {
		fmt.Println(err)
		return
	}
	defer q.Close()

	for i := 1; i <= 10; i++ {
		q.Exec("insert into user set name=?", time.Now().String())
	}

	q.Exec("delete from user where id=?", 1)
	q.Exec("update user set name=? where id=?", "new name", 2)

	user := new(User)
	q.QueryRow("select * from user where id=?", 3).Scan(&user.Id, &user.Name)
	fmt.Println(user)

	var users []*User
	rows, _ := q.Query("select * from user")
	for rows.Next() {
		user := new(User)
		rows.Scan(&user.Id, &user.Name)
		fmt.Println(user)
		users = append(users, user)
	}
}
共0个回复