(三)go-sql-driver

1. go-sql-driver/mysql

2. CRUD 示例

// mysql_demo project main.go
package main

import (
    "database/sql"
    "fmt"

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

func MysqlTest() {
    db, err := sql.Open("mysql", "root:123456@tcp(127.0.0.1:3306)/ld")
    if err != nil {
        fmt.Println("connect to mysql failed!")
        return
    } else {
        fmt.Println("connected")
    }
    defer db.Close()

    err = db.Ping()
    if err != nil {
        panic(err.Error())
    }

    // select
    sqlSelect := "select * from ld.pet"
    statement, err := db.Prepare(sqlSelect)
    if err != nil {
        fmt.Println("prepare statement failed:", err.Error())
        return
    }
    defer statement.Close()
    rows, err := statement.Query()
    if err != nil {
        fmt.Println("query failed:", err.Error())
    }
    columns, err := rows.Columns()
    if err != nil {
        fmt.Println(err.Error())
        return
    }
    fmt.Println(columns)

    row := make([]sql.RawBytes, len(columns))
    scanArgs := make([]interface{}, len(row))
    for i := range row {
        scanArgs[i] = &row[i]
    }

    for rows.Next() {
        err := rows.Scan(scanArgs...)
        if err != nil {
            panic(err.Error())
        }
        // row
        for pos, col := range row {
            fmt.Println(columns[pos], ":", string(col))
        }
        fmt.Println()
    }

    // insert
    sqlInsert := "insert into ld.pet values('kk', 'ld', \"2018-12-13\", \"2018-12-13 15:56:50\", \"2018-12-13 15:57:00\")"
    statement_insert, err := db.Prepare(sqlInsert)
    if err != nil {
        panic(err.Error())
    }
    statement_insert.Exec()
    statement_insert.Close()

    // delete
    sqlDelete := "delete from ld.pet where name = 'kk'"
    statement_delete, err := db.Prepare(sqlDelete)
    if err != nil {
        panic(err.Error())
    }
    statement_delete.Exec()
    statement_delete.Close()

    // update
    sqlUpdate := "update ld.pet set ower = 'caicai' where name = 'gg'"
    statement_update, err := db.Prepare(sqlUpdate)
    if err != nil {
        panic(err.Error())
    }
    statement_update.Exec()
    statement_update.Close()

}

func main() {
    fmt.Println("Hello World!")
    MysqlTest()
}

转载于:https://www.cnblogs.com/walkinginthesun/p/10114960.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值