go sqlx基本使用

1.表结构

CREATE TABLE `user` (
  `user_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `username` varchar(260) DEFAULT '嘎嘎',
  `sex` varchar(260) DEFAULT NULL,
  `email` varchar(260) DEFAULT NULL,
  `json` json DEFAULT NULL,
  `create_time` int(10) NOT NULL,
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;

2.go代码

package main

import (
	"encoding/json"
	"fmt"
	 _"github.com/go-sql-driver/mysql"
	"github.com/jmoiron/sqlx"
	"log"
	"strconv"
	"time"
)

type Person struct {
	UserId   int    `db:"user_id"`
	Username string `db:"username"`
	Sex      string `db:"sex"`
	Email    string `db:"email"`
	Json     string `db:"json"`
	Ctime    string `db:"create_time"`
}

var Db *sqlx.DB

func init() {
	db_username := "root" //用户名
	db_passwold := "root" //密码
	db_databases := "go" // 库
	dsn := fmt.Sprintf("%s:%s@tcp(127.0.0.1:3306)/%s", db_username, db_passwold, db_databases)
	database, err := sqlx.Open("mysql", dsn)
	if err != nil {
		fmt.Println("open mysql failed,", err)
		return
	}
	Db = database
}

//插入数据
func insert(){
	json_map := make(map[string]string,10)
	json_map["key"] = "srfzvqwe"
	json_map["code"] = "123456"

	mjson,_ :=json.Marshal(json_map)
	String_json :=string(mjson)

	insert_json_data := Person{
		Username : "lgx",
		Sex		 : "nan",
		Email 	 : "[email protected]",
		Json	 :  String_json,
		Ctime    :  strconv.FormatInt(time.Now().Unix(),10),
	}


	sql := `insert into user (username, sex, email, json, create_time) values (?, ?, ?, ?, ?)`
	res := Db.MustExec(sql,
		insert_json_data.Username,
		insert_json_data.Sex,
		insert_json_data.Email,
		insert_json_data.Json,
		insert_json_data.Ctime,
	)
	insery_id , _ := res.LastInsertId()
	fmt.Println(insery_id)
	defer Db.Close()
}

//修改数据
func updateUser()  {
	sql := `update user set username = ?, sex = ? where user_id = ?`
	res, err := Db.Exec(sql, "德玛西亚", 28, 1)
	if err != nil {
		log.Fatal(err)
	}
	update_row,_ := res.RowsAffected()
	fmt.Println("update_row : ",update_row)
	defer Db.Close()
}


// 查询数据
func selectUser() {
	sql := `select * from user where user_id > 1`
	var user []Person
	err := Db.Select(&user, sql)
	var c_time int64
	var ok error
	for i,v := range user {
		c_time,ok  = strconv.ParseInt(v.Ctime, 10, 64)
		if ok != nil{
			log.Fatal("ParseInt fail...")
		}
		user[i].Ctime = time.Unix(c_time , 0).Format("2006-01-02 15:04:05")
	}
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(user)
}

// 查询一条数据
func getNum() {
	var num int
	_ = Db.Get(&num, "select count(*) from user")
	fmt.Printf("数据库一共有:%d 个用户\n", num)
	var u Person
	_ = Db.Get(&u, "select user_id, username, sex, email, json from user where sex = ?","nan")
	fmt.Println("数据:", u)
}

func deleteUser() {
	sql := `delete from user where user_id = 5`
	result, _ := Db.Exec(sql)
	num, _ := result.RowsAffected() // 受影响行数
	fmt.Println(num)
}
//事务处理
func events() {
	tx, _ := Db.Beginx()
	_, err1 := tx.Exec("update user set sex = 11 where user_id = 1")
	_, err2 := tx.Exec("update user set sex = 12 where user_id = 2")
	fmt.Println(err1, err2)
	if err1 != nil || err2 != nil {
		tx.Rollback()

	}
	tx.Commit()
}



func main() {
	//updateUser()
	//insert()
	//selectUser()
	//getNum()
	//deleteUser()
	events()
}

你可能感兴趣的:(golang,go,sqlx基本使用)