Go 读写mysql

Submitted by Lizhe on Thu, 10/25/2018 - 18:00

package main

 

import (

    "database/sql"

    "log"

 

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

)

 

func checkErr(err error) {

 

    if err != nil {

 

        //log.Println(err)

 

    }

 

}

 

func main() {

 

    db, err := sql.Open("mysql", "root:root@tcp(172.28.128.4:3306)/test?charset=utf8")

    defer db.Close()

    checkErr(err)

 

    //stmt, err := db.Prepare("INSERT students SET name=?,age=?")

    //res, err := stmt.Exec("lizhe", "20")

    //log.Println(res)

 

    var name string

    var age string

    selectErr := db.QueryRow("SELECT name,age FROM students WHERE id=?", 1).Scan(&name, &age)

    log.Println(name + ":" + age)

 

    rows, err := db.Query("SELECT id,name,age FROM students222")

    defer rows.Close()

 

    for rows.Next() {

        var (

            id int

            name string

            age int

        )

        err := rows.Scan(&id, &name, &age)

        if err != nil {

            log.Fatal(err)

        }

        log.Println(id, name, age)

    }

 

    checkErr(selectErr)

}