1.打开命令行
输入 go get github.com/go-sql-driver/mysql
2.输入go env查看一下gopath的路径,我们的驱动就在那里
3.创建数据库 test,创建表player,创建字段 age、name,如图(建议使用可视化工具)
5.在我们ide中添加如下代码
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
func main() {
db, err := sql.Open("mysql", "root:root@tcp(127.0.0.1:3306)/test?charset=utf8")
if err != nil {
fmt.Println(err)
return
}
defer db.Close()
var result sql.Result
result, err = db.Exec("insert into palyer(age, name) values(?,?)", 16, "tom")
if err != nil {
fmt.Println(err)
return
}
lastId, _ := result.LastInsertId()
fmt.Println("新插入记录的ID为", lastId)
var row *sql.Row
row = db.QueryRow("select * from t_test")
var name string
var id, age int
err = row.Scan(&id, &age, &name)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(id, "\t", name, "\t", age)
result, err = db.Exec("insert into t_test(age, name) values(?,?)", 24, "black")
var rows *sql.Rows
rows, err = db.Query("select * from t_test")
if err != nil {
fmt.Println(err)
return
}
for rows.Next() {
var name string
var id, age int
rows.Scan(&id, &age, &name)
fmt.Println(id, "\t", name, "\t", age)
}
rows.Close()
db.Exec("truncate table t_test")
}
6.运行代码,刷新一下可视化工具,看看数据库有没有新增内容
7.66666666666666666666666的起飞了。开发速度快的吓人~~~~~~~~~~
所有评论(0)