Go 操作mysql使用举例---连接本地数据库

Posted 翔云

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Go 操作mysql使用举例---连接本地数据库相关的知识,希望对你有一定的参考价值。

连接数据库的方式有两种:TCP和Unix域socket。
本文使用Unix domain sockets连接数据库。关于TCP连接数据库可以参考Go 操作mysql使用举例

下面例子中,演示了使用show命令查看数据库连接信息的过程。

mysql> show processlist;
+----+------+----------------------+------+---------+------+----------+------------------+
| Id | User | Host | db | Command | Time | State | Info |
+----+------+----------------------+------+---------+------+----------+------------------+
| 26 | root | 172.24.232.66:7868 | sys | Query | 0 | starting | show processlist |
+----+------+----------------------+------+---------+------+----------+------------------+
1 row in set (0.00 sec)

代码如下:

package main

import (
	"database/sql"
	"fmt"
	"log"

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

)

type DBConnectionInfo struct {
	ID	[]byte
	User	string
	Host	string
	DB	[]byte 
	Cmd	string
	Time	[]byte
	State	string
	Info	[]byte
}

func(f *DBConnectionInfo) String() string{

	return fmt.Sprintf("ID:%s, User:%s, Host:%s, DB:%s, Cmd:%s, Time:%s, State:%s, Info:%s", string(f.ID), f.User, f.Host, string(f.DB), f.Cmd, string(f.Time), f.State, string(f.Info))

}

const (
	mysqlShowProcessList="show processlist"
)
var DB *sql.DB

//var dataBase = "root:Aa123456@unix(/tmp/mysql.sock)/mysql"
var dataBase = "root:Aa123456@unix(/tmp/mysql.sock)/"

func Init() {
	var err error
	DB, err = sql.Open("mysql", dataBase)
	if err != nil {
		log.Fatalln("open db fail:", err)
	}

	err = DB.Ping()
	if err != nil {
		log.Fatalln("ping db fail:", err)
	}
}

func main() {

	Init()

	query()

}


func query() {

	rows, err := DB.Query(mysqlShowProcessList)
	if err != nil {
		log.Println("query failed:", err)
		return
	}
	defer rows.Close()

	for rows.Next(){
		data := &DBConnectionInfo{}
		if err := rows.Scan(&data.ID, &data.User, &data.Host, &data.DB, &data.Cmd, &data.Time, &data.State, &data.Info); err != nil {
			log.Println("Scan failed:", err)
		}

		fmt.Println("data:", data)
	}


}


output:

data: ID:145, User:root, Host:localhost, DB:, Cmd:Sleep, Time:632, State:, Info:
data: ID:172, User:root, Host:localhost, DB:, Cmd:Query, Time:0, State:starting, Info:show processlist

参考

https://blog.csdn.net/lanyang123456/article/details/79831537

https://www.cnblogs.com/hanyouchun/p/6708037.html

以上是关于Go 操作mysql使用举例---连接本地数据库的主要内容,如果未能解决你的问题,请参考以下文章

Go语言中mysql数据库操作

Go基础之--操作Mysql

Go mysql使用举例

Go操作MySQL

Go语言中mysql数据库操作

Go语言操作MySQL