GitHub给出一个简单的方法 就算是直接 cmd
go get github.com/go-sql-driver/mysql
一直提示我没有设置GOPATH 实际上设置了 结果………………
后来直接下载 MySQL支持库 https://github.com/go-sql-driver/mysql 解压
在路径 C:\Go\src\pkg\github.com(需新建)\go-sql-driver(需新建)\(这里放刚刚解压的mysql)
完整路径 C:\Go\src\pkg\github.com\go-sql-driver\mysql
不明白的回复我 !!
CREATE TABLE `user` (
`username` varchar(255) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
`id` int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`)
)
go_mysql.go
package main
import (
"database/sql"
_ "github.com/go-sql-driver/mysql"
"log"
)
func insert(db *sql.DB) {
stmt, err := db.Prepare("INSERT INTO user(username, password) VALUES(?, ?)")
defer stmt.Close()
if err != nil {
log.Println(err)
return
}
stmt.Exec("Demon", "Demon")
stmt.Exec("user", "123123")
}
func main() {
//db, err := sql.Open("mysql","root:passwd@tcp(localhost:3306)/datebase?charset=utf8") 连接远程数据方法
db, err := sql.Open("mysql","root:passwd@/datebase")
//db, err := sql.Open("mysql","root:@/test")
if err != nil {
log.Fatalf("Open database error: %s\n", err)
}
defer db.Close()
err = db.Ping()
if err != nil {
log.Fatal(err)
}
insert(db)
rows, err := db.Query("select id, username from user where id = ?", 1)
if err != nil {
log.Println(err)
}
defer rows.Close()
var id int
var name string
for rows.Next() {
err := rows.Scan(&id, &name)
if err != nil {
log.Fatal(err)
}
log.Println(id, name)
}
err = rows.Err()
if err != nil {
log.Fatal(err)
}
}
Good Luck!
0
顶
3
踩
分享到:
2014-11-17 10:43
浏览 966
评论