连接数据库的方式有两种:TCP和Unix域socket。
本文使用Unix domain sockets连接数据库。关于TCP连接数据库可以参考Go 操作mysql使用举例
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:[email protected](/tmp/mysql.sock)/mysql"
var dataBase = "root:[email protected](/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
原文地址:https://www.cnblogs.com/lanyangsh/p/9783615.html
时间: 2024-10-05 12:33:18