本文主要是介绍【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 mainimport ("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 stringerr = 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语言读取mysql】go语言连接mysql,并且查询出结果的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!