golang操做mysql數據庫

golang操做mysql數據庫mysql

代碼: mysql的增、刪、改、查git

package main

import (
    "database/sql"
    "fmt"
    "strconv"
    "time"

    _ "github.com/go-sql-driver/mysql"
)

func main() {

    db, err := sql.Open("mysql", "root:Admin!1234@tcp(10.99.2.153:3306)/xes_nrcp?charset=utf8")
    defer db.Close()
    checkErr(err)

    //插入數據
    insert(21, db)

    //刪除數據
    delete(14, db)

    //更新數據
    update(15, "設計部門", db)

    //查詢數據
    get(db)

}

func checkErr(err error) {
    if err != nil {
        panic(err)
    }
}

func get(db *sql.DB) {
    rows, _ := db.Query("SELECT * FROM aaa_test")
    cloumns, _ := rows.Columns()

    //獲取列字段
    for _, cloumn := range cloumns {
        fmt.Print(cloumn + " ")
    }
    fmt.Println()

    //遍歷返回結果
    for rows.Next() {
        rows.Scan(&cloumns[0], &cloumns[1], &cloumns[2], &cloumns[3])
        fmt.Println(cloumns[0], cloumns[1], cloumns[2], cloumns[3])
    }
}

func insert(id int, db *sql.DB) {
    //插入數據方式

    stmt, _ := db.Prepare("INSERT aaa_test SET id=?,nameA=?,descA=?")
    res, _ := stmt.Exec(id, "研發部門", "2012-12-09", time.Now())
    resID, _ := res.LastInsertId()
    fmt.Println(resID)

    //or
    // stmt, _ := db.Prepare("INSERT aaa_test (id,nameA,descA,createTime)values (?,?,?,?)")
    // res, _ := stmt.Exec(17, "研發部門", "2012-12-09", time.Now())
    // id, _ := res.LastInsertId()
    // fmt.Println(id)

    //or
    // res, _ := db.Exec("INSERT aaa_test (id,nameA,descA)values (?,?,?)", 18, "研發部門", "2012-12-09")
    // id, _ := res.LastInsertId()
    // fmt.Println(id)

    //or
    // db.Exec("INSERT aaa_test (id,nameA,descA,createTime)values (?,?,?,?)", 14, "qwe", "2012-12-09", time.Now())

    //or
    //db.Exec("INSERT aaa_test SET id=?,nameA=?,descA=?,createTime=?", id, "研發部門", "寫寫代碼", time.Now())

}

func delete(id int, db *sql.DB) {
    stmt, err := db.Prepare("delete from aaa_test where id=?")
    checkErr(err)

    res, err := stmt.Exec(id)
    checkErr(err)

    affect, err := res.RowsAffected()
    checkErr(err)
    fmt.Println("刪除數據影響行數:" + strconv.FormatInt(affect, 10))

}

func update(id int, name string, db *sql.DB) {
    stmt, err := db.Prepare("update aaa_test set nameA=? where id=?")
    checkErr(err)

    res, err := stmt.Exec(name, id)
    checkErr(err)

    affect, err := res.RowsAffected()
    checkErr(err)

    fmt.Println(affect)
}

sql.Open()函數用來打開一個註冊過的數據庫驅動,go-sql-driver中註冊了mysql這個數據庫驅動,第二個參數是DSN(Data Source Name),它是go-sql-driver定義的一些數據庫連接和配置信息。它支持以下格式:github

  user@unix(/path/to/socket)/dbname?charset=utf8   user:password@tcp(localhost:5555)/dbname?charset=utf8   user:password@/dbname   user:password@tcp([de:ad:be:ef::ca:fe]:80)/dbname 

db.Prepare()函數用來返回準備要執行的sql操做,而後返回準備完畢的執行狀態。golang

db.Query()函數用來直接執行Sql返回Rows結果。sql

stmt.Exec()函數用來執行stmt準備好的SQL語句數據庫

咱們能夠看到咱們傳入的參數都是=?對應的數據,這樣作的方式能夠必定程度上防止SQL注入。socket

相關文章
相關標籤/搜索