go语言连接mysql数据库
php虽然开发速度快,但是性能实在是有待提高。
C和C++?不擅长,读别人的代码都有困难,更不要提自己写了。
经人介绍,开始使用go语言,开发速度比较快,性能也还不错。
http://golang.org/
最近需要使用go语言连接mysql数据库,
第一反应是去找官方的package:
http://golang.org/pkg/database/
有二个package,看起来都不靠谱:
sql:
Package sql provides a generic interface around SQL (or SQL-like) databases.
driver:
Package driver defines interfaces to be implemented by database drivers as used by package sql.
然后去 Go Project Dashboard 找找看,http://godashboard.appspot.com/
有几个mysql相关的:
GoMySQL - MySQL library for Go lib
GoMySQL-Client-Library - Go MySQL Client Library lib
MyMySQL - MySQL Client API written entirely in Go. lib
go-dbd-mysql - A MySQL driver implementation for go-dbi lib
go-dbi - A database abstraction API in the spirit of Perl DBI et al lib
go-mysql - MySQL wrapper for Go cgo
go-mysql-driver - A lightweight and fast MySQL-Driver for Go's database/sql package lib
libmysqlgo - Another wrapper for the MySQL C API cgo
mysql-connector-go - implements MySQL wire protocol lib
mysqlgo - MySQL bindings cgo
GoMySQL go-dbd-mysql go-dbi go-mysql 安装不了…不知道是环境问题还是什么问题,没细看。
GoMySQL-Client-Library 与 libmysqlgo 链接到404出错页面。
mysql-connector-go 链接到403出错页面…
mysqlgo已经defunct。
MyMySQL与go-mysql-driver安装成功。
先看go-mysql-driver:
package main
import (
"fmt"
)
import "database/sql"
import _ "code.google.com/p/go-mysql-driver/mysql"
func main() {
db, _ := sql.Open("mysql", "test:123456@tcp(localhost:3306)/shipincon?charset=utf8")
row := db.QueryRow("select nickname from user limit 1")
var nickname string
row.Scan(&nickname)
fmt.Println(nickname)
db.Exec("truncate table t");
db.Exec("insert into t (select * from user order by user_id ASC limit 5)")
rows, _ := db.Query("select nickname, user_id, type from t limit 2");
for rows.Next() {
var nickname string
var t string
var user_id string
rows.Scan(&nickname, &user_id, &t)
fmt.Println(nickname, user_id , t)
}
}
[root@www go]# go run test.go
赵天化
赵天化 1 renren
刘流 2 renren
看起来不错,挺好用的。
缺点?
rows.Scan的时候,表中的每一个col都需要一个变量与之对应,字段多了不要累死?
MyMySQL在这方面就表现的比较好了:
package main
import (
"fmt"
//"os"
"github.com/ziutek/mymysql/mysql"
_ "github.com/ziutek/mymysql/native" // Native engine
// _ "github.com/ziutek/mymysql/thrsafe" // Thread safe engine
)
func main() {
db := mysql.New("tcp", "", "127.0.0.1:3306", "test", "123456", "shipincon")
err := db.Connect()
if err != nil {
panic(err)
}
db.Query("set names utf8")
rows, res, err := db.Query("select nickname,type,user_id from user where user_id > %d limit 2", 20)
if err != nil {
panic(err)
}
for _, row := range rows {
first := res.Map("user_id")
second := res.Map("type")
third := res.Map("nickname")
val1, val2, val3 := row.Int(first), row.Str(second), row.Str(third)
fmt.Println(val1, val2,val3 )
}
}
[root@www go]# go run t.go
34 renren 赵天祥
35 renren 刘静
看起来MyMySQL更加成熟一些。
官方文档:
http://go.pkgdoc.org/github.com/ziutek/mymysql
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。