2019-05-12
Go读取Mysql数据 (minirplus.com)
Go读取Mysql数据 最近在测试将frp验证与SSRPanel数据库进行结合,其中有一个主要的核心功能就是从SSRPanel数据库中读取用户列表,frp基于Go,所以需要验证如何在Go中使用mysql接口。 环境创建测试项目 - mkdir -p work/src/my_project/testMysql
复制代码创建测试文件
- nano ~/work/src/my_project/testMysql/testMysql.go
复制代码 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 Morehttps://github.com/go-sql-driver/mysql https://github.com/go-sql-driver/mysql/wiki/Examples
2019-05-12
Go读取Mysql数据 (minirplus.com)
|