Go读取Mysql数据
最近在测试将frp验证与SSRPanel数据库进行结合,其中有一个主要的核心功能就是从SSRPanel数据库中读取用户列表,frp基于Go,所以需要验证如何在Go中使用mysql接口。
环境
- Debian 9
- Go环境
创建测试项目
1 |
mkdir -p work/src/my_project/testMysql |
创建测试文件
1 |
nano ~/work/src/my_project/testMysql/testMysql.go |
testMysql.go
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
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) } |
加载外部参照
1 |
go get -u github.com/go-sql-driver/mysql |
编译项目
1 |
go install my_project/testMysql |
运行
1 |
testMysql |
返回
1 |
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
There are no comments yet