Golang 操作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

上一篇:DB文件会生成在哪里以及生成的个数是多少?


下一篇:mysql存储过程和函数