majianyu
2/26/2018 - 9:21 AM

go_mysql

package db

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

var Db *sql.DB

func init() {
    var err error
    Db, err = sql.Open("mysql", "root:root@tcp(127.0.0.1:3306)/gwp?charset=utf8&parseTime=true&loc=Asia%2FShanghai")
    //Db, err = sql.Open("mysql", "root:root@tcp(127.0.0.1:3306)/gwp?charset=utf8&loc=Asia%2FShanghai")
    if err != nil {
        panic(err)
    }
}
func InsertData(sqlStr string, params ...interface{}) {
    stmt, _ := Db.Prepare(sqlStr)
    defer stmt.Close()
    result, err := stmt.Exec(params...)
    if err != nil {
        panic(err)
    }
    fmt.Println(result.LastInsertId())
    fmt.Println(result.RowsAffected())
}
func Query(sqlStr string, params ...interface{}) (*sql.Rows, error) {
    rows, err := Db.Query(sqlStr, params...)
    if err != nil {
        return nil, err
    }
    return rows, nil
}
func QueryOne(sqlStr string, params ...interface{}) *sql.Row {
    row := Db.QueryRow(sqlStr, params...)
    return row
}
func UpdateData(sqlStr string, params ...interface{}) {
    stmt, _ := Db.Prepare(sqlStr)
    defer stmt.Close()
    result, err := stmt.Exec(params...)
    if err != nil {
        panic(err)
    }
    fmt.Println(result.LastInsertId())
    fmt.Println(result.RowsAffected())
}
func DeleteData(sqlStr string, params ...interface{}) {
    stmt, _ := Db.Prepare(sqlStr)
    defer stmt.Close()
    result, err := stmt.Exec(params...)
    if err != nil {
        panic(err)
    }
    fmt.Println(result.LastInsertId())
    fmt.Println(result.RowsAffected())
}