【go语言读取mysql】go语言连接mysql,并且查询出结果

一、需求分析
go语言 连上mysql,并且从mysql中读取数据

二、实现效果

"D:\Program Files (x86)\JetBrains\Gogland 171.3780.106\bin\runnerw.exe" D:/Go\bin\go.exe run D:/Go/code/src/awesomeProject/go_mysql.go
链接数据库成功...........已经打开
192002628163
192002628163
192002627657
192002629069
192002629069
链接数据库成功...........已经关闭

Process finished with exit code 0

三、实现源代码

package main

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

    "github.com/widuu/gojson"
)

var (
    dbhostsip  = "主机"
    dbusername = "用户名称"
    dbpassowrd = "数据库密码"
    dbname     = "数据库名称"
)


type mysql_db struct {
    db *sql.DB  //定义结构体
}

func (f *mysql_db) mysql_open() { //打开
    Odb, err := sql.Open("mysql", dbusername+":"+dbpassowrd+"@tcp("+dbhostsip+")/"+dbname)
    if err != nil {
        fmt.Println("链接失败")
    }
    fmt.Println("链接数据库成功...........已经打开")
    f.db = Odb
}

func (f *mysql_db) mysql_close() { //关闭
    defer f.db.Close()
    fmt.Println("链接数据库成功...........已经关闭")
}




func (f *mysql_db) mysql_select(sql_data string) {
    rows, err := f.db.Query(sql_data)
    if err != nil {
        println(err)
    }
    for rows.Next() {
        var in_param string


        err = rows.Scan(&in_param)
        if err != nil {
            panic(err)
        }

        user_id:=gojson.Json(in_param).Get("user_id").Tostring()
        fmt.Println(user_id)

    }
}

func main() {
    db := &mysql_db{}
    db.mysql_open()
    db.mysql_select("SELECT in_param FROM t_rong_credit_bank a WHERE a.method_code IN ('010402')  limit 10 ")
    db.mysql_close() //关闭
}

你可能感兴趣的:(编程开发-go语言)