| 
 
 2019-05-12
 
 Go读取Mysql数据 (minirplus.com)
 
 
 
 Go读取Mysql数据 最近在测试将frp验证与SSRPanel数据库进行结合,其中有一个主要的核心功能就是从SSRPanel数据库中读取用户列表,frp基于Go,所以需要验证如何在Go中使用mysql接口。环境 创建测试项目 复制代码mkdir -p work/src/my_project/testMysql
创建测试文件
 testMysql.go复制代码nano ~/work/src/my_project/testMysql/testMysql.go
 加载外部参照复制代码package main
 
import (
        "database/sql"
        "fmt"
        _ "github.com/go-sql-driver/mysql"
)
 
func main() {
        db, err := sql.Open("mysql", "user:password@/ssrpanel")
        if err != nil {
                panic(err.Error())  // Just for example purpose. You should use proper error handling instead of panic
        }
        defer db.Close()
 
        // Prepare statement for reading data
        stmtOut, err := db.Prepare("SELECT port FROM user WHERE id = ?")
        if err != nil {
                panic(err.Error()) // proper error handling instead of panic in your app
        }
        defer stmtOut.Close()
 
        var squareNum int // we "scan" the result in here
 
        // Query the port-number of user id = 4
        err = stmtOut.QueryRow(4).Scan(&squareNum) // WHERE id = 4
        if err != nil {
                panic(err.Error()) // proper error handling instead of panic in your app
        }
        fmt.Printf("The port number of 4 is: %d", squareNum)
}
 
 编译项目复制代码go get -u github.com/go-sql-driver/mysql
 
 运行复制代码go install my_project/testMysql
 返回
 
 
 复制代码The port number of 4 is: 17643
测试成功!
 
 Know  More
 https://github.com/go-sql-driver/mysql https://github.com/go-sql-driver/mysql/wiki/Examples 
 2019-05-12
 
 Go读取Mysql数据 (minirplus.com)
 
 
 |