飞克网

标题: GO操作Mysql数据库 [打印本页]

作者: admin    时间: 2018-4-8 22:40
标题: GO操作Mysql数据库
1、使用github.com/go-sql-driver/mysql和github.com/jmoiron/sqlx这个驱动包和工具类,打开cmd窗口输入:go get github.com/go-sql-driver/mysql和go get github.com/jmoiron/sqlx,会下载到你的GOPATH路径的src 下

2、导入驱动包
import (    "database/sql"    _ "github.com/go-sql-driver/mysql")
3、链接数据库
db, err := sql.Open("mysql",        "user:password@tcp(127.0.0.1:3306)/hello")  

  if err != nil {   
     log.Fatal(err)  
  }  
  defer db.Close()

4、插入数据
r, err := Db.Exec("insert into person(username,sex,email)values(?,?,?)", "stu004", "man", "stu001@qq.com")
if err != nil {
  fmt.Println("exec1 failed,", err)
  return
}
id, err := r.LastInsertId()//返回插入数据ID
if err != nil {
  fmt.Println("exec2 failed,", err)
  return
}
fmt.Println("insert succ:", id)

5、查询数据
var person []Person
err := Db.Select(&person, "select * from person")
if err != nil {
  fmt.Println("exec_select failed,", err)
  return
}
fmt.Println("select succ:", person)

6、更新数据
_, err := Db.Exec("update person set username=? where user_id=?", "stu011", 1)
if err != nil {
  fmt.Println("exec_update failed,", err)
  return
}
fmt.Println("更新成功")

7、删除数据
_, err := Db.Exec("delete from person where user_id=?", 10)
if err != nil {
  fmt.Println("exec_delete failed,", err)
  return
}
fmt.Println("删除成功")








欢迎光临 飞克网 (http://www.feikechina.com/) Powered by Discuz! X3.2