模块安装

go get -u github.com/go-sql-driver/mysql

代码

package main

import (

"database/sql"

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

"log"

"fmt"

)

func main(){

db,err :=sql.Open("mysql","root:@tcp(127.0.0.1:3306)/nginxlog") //连接数据库

checkErr(err)

rows,err :=db.Query("select * from nginxlog limit 10; ")

checkErr(err)

for rows.Next(){

var id int

var ip string

var time string

var methods string

var source string

var protocol string

var status string

err = rows.Scan(&id,&ip,&time,&methods,&protocol,&status,&source)

checkErr(err)

fmt.Println(id,ip,time,methods,status,source)

}

}

//校验函数

func checkErr(err error){

if err != nil{

log.Println(err)

}

}

数据库的数据内容

c85800655ed6a26dcdc28cf1df2ddf42.png

Golang查询的结果:

d4cc5b4598e5cc5a41aa1529c524e1b1.png