一個封裝的Goland資料庫操作方法集

來源:互聯網
上載者:User

使用原生的Golang進行資料庫CRUD感覺到諸多不變,於是參照之前使用資料庫類的習慣用法,
封裝了一個資料庫操作方法集:

package libimport (    "database/sql"    _ "github.com/go-sql-driver/mysql"    "strings"    "fmt")type dbRow map[string]interface{}type Dblib struct {    db *sql.DB}func NewDblib(driver, dsn string) (*Dblib, error) {    db, err := sql.Open(driver, dsn)    if err != nil {        return nil, err    }    err = db.Ping()    if err != nil {        return nil, err    }    p := new(Dblib)    p.db = db    return p, nil}func scanRow(rows *sql.Rows) (dbRow, error) {    columns, _ := rows.Columns()    vals := make([]interface{}, len(columns))    valsPtr := make([]interface{}, len(columns))    for i := range vals {        valsPtr[i] = &vals[i]    }    err := rows.Scan(valsPtr...)    if err != nil {        return nil ,err    }    r := make(dbRow)    for i, v := range columns {        if va, ok := vals[i].([]byte); ok {            r[v] = string(va)        } else {            r[v] = vals[i]        }    }    return r, nil}// 擷取一行記錄func (d *Dblib) GetOne(sql string, args ...interface{}) (dbRow, error) {    rows, err := d.db.Query(sql, args...)    if err != nil {        return nil, err    }    defer rows.Close()    rows.Next()    result, err := scanRow(rows)    return result, err}// 擷取多行記錄func (d *Dblib) GetAll(sql string, args ...interface{}) ([]dbRow, error) {    rows, err := d.db.Query(sql, args...)    if err != nil {        return nil, err    }    defer rows.Close()    result := make([]dbRow, 0)    for rows.Next() {        r, err := scanRow(rows)        if err != nil {            continue        }        result = append(result, r)    }    return result, nil}// 寫入記錄func (d *Dblib) Insert(table string, data dbRow) (int64, error) {    fields := make([]string, 0)    vals := make([]interface{}, 0)    placeHolder := make([]string, 0)    for f, v := range data {        fields = append(fields, f)        vals = append(vals, v)        placeHolder = append(placeHolder, "?")    }    sql := fmt.Sprintf("INSERT INTO %s(%s) VALUES(%s) ", table, strings.Join(fields, ","), strings.Join(placeHolder, ","))    result, err := d.db.Exec(sql, vals...)    if err != nil {        return 0, err    }    lID, err := result.LastInsertId()    if err != nil {        return 0, err    }    return lID, nil}// 更新記錄func (d *Dblib) Update(table, condition string, data dbRow, args ...interface{}) (int64, error) {    params := make([]string, 0)    vals := make([]interface{}, 0)    for f, v := range data {        params = append(params, f + "=?")        vals = append(vals, v)    }    sql := "UPDATE %s SET %s"    if condition != "" {        sql += " WHERE %s"        sql = fmt.Sprintf(sql, table, strings.Join(params, ","), condition)        vals = append(vals, args...)    } else {        sql = fmt.Sprintf(sql, table, strings.Join(params, ","))    }    result, err := d.db.Exec(sql, vals...)    if err != nil {        return 0, err    }    aID, err := result.RowsAffected()    if err != nil {        return 0, err    }    return aID, nil}// 刪除記錄func (d *Dblib) Delete(table, condition string, args ...interface{}) (int64, error) {    sql := "DELETE FROM %s "    if condition != "" {        sql += "WHERE %s"        sql = fmt.Sprintf(sql, table, condition)    } else {        sql = fmt.Sprintf(sql, table)    }    result, err := d.db.Exec(sql, args...)    if err != nil {        return 0, err    }    aID, err := result.RowsAffected()    if err != nil {        return 0, err    }    return aID, nil}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.