golang使用sqlx第三方包进行数据的CURD操作

package main

import(
	"fmt"
	_"github.com/go-sql-driver/mysql"
	"github.com/jmoiron/sqlx"
)

var Dbx *sqlx.DB

func initXDb() error {
	var err error
	dsn := "root:abc@198920@tcp(localhost:3306)/golang"
	Dbx,err = sqlx.Open("mysql",dsn)
	if err != nil {
		fmt.Printf("init db connection instance falield:%v\n",err)
		return err
	}
	return  nil
}

type Clazz struct{
	Id int `db:"id"`
	Name string `db:"name"`
	ClazzId int `db:"clazz_id"`
	Age int `db:"age"`
	Sex string `db:"sex"`
}

func addClazz(c *Clazz){
	insert := "INSERT INTO clazz(name,clazz_id,age,sex)VALUES(?,?,?,?)"
	result,err := Dbx.Exec(insert,c.Name,c.ClazzId,c.Age,c.Age)
	if err != nil {
		fmt.Printf("exec %s failed:%v\n",insert,err)
		return
	}
	code,err := result.LastInsertId()
	if err != nil {
		fmt.Printf("get last id failed:%v\n",err)
		return
	}
	fmt.Printf("last id :%d\n",code)
}

func delById(id int){
	del := "DELETE FROM clazz where id=?"
	result,err := Dbx.Exec(del,id)
	if err != nil {
		fmt.Printf("exec %s failed:%v\n",err)
		return
	}
	affectedId,err := result.RowsAffected()
	if err != nil {
		fmt.Printf("get affected id failed:%v\n",err)
		return
	}
	fmt.Printf("affected row:%d\n",affectedId)
}


func updateClazz(c *Clazz){

	update := "UPDATE clazz SET name=?, clazz_id=? age=?,sex=? WHERE id=?"
	stmt,err := Dbx.Prepare(update)
	if err != nil {
		fmt.Printf("prepare %s failed:%v\n",update,err)
		return
	}

	defer func() {
		if stmt != nil {
			stmt.Close()
		}
	}()

	result,err := stmt.Exec(c.Name,c.ClazzId,c.Age,c.Sex)
	if err != nil {
		fmt.Printf("exec %s failed:%v\n",update,err)
		return
	}
	affectedId,err := result.RowsAffected()
	if err != nil {
		fmt.Printf("get affected row failed:%v\n",err)
		return
	}
	fmt.Printf("affected row:%d\n",affectedId)
}

func findByName(name string) (err error,clazz []Clazz) {
	selectSql := "SELECT * FROM clazz WHERE name=?"
	err = Dbx.Select(&clazz,selectSql,name)
	return
}

func findById(id int) (err error,clazz Clazz) {
	selectSql := "SELECT id,name,clazz_id,age,sex FROM clazz WHERE id=?"
	err = Dbx.Get(&clazz,selectSql,id)
	return
}

func main()  {
	initXDb()
	_ = Clazz{
		Name:    "Lisa",
		ClazzId: 10001,
		Age:     22,
		Sex:     "女",
	}
	//addClazz(&clazz)
	err,c := findById(2)
	if err != nil {
		fmt.Printf("faield:%v\n",err)
		return
	}
	fmt.Printf("%#v\n",c)
}

你可能感兴趣的:(golang编程学习)