golang中使用mysql数据库

安装

安装mysql驱动

go get github.com/go-sql-driver/mysql

安装sqlx驱动

go get github.com/jmoiron/sqlx

一.插入数据库

package main

import (
"fmt" _ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
) type Person struct {
UserId int `db:"user_id"`
Username string `db:"username"`
Sex string `db:"sex"`
Email string `db:"email"`
} var Db *sqlx.DB func init() {
  //与数据库建立连接
database, err := sqlx.Open("mysql", "root:123@tcp(127.0.0.1:3306)/test")
if err != nil {
fmt.Println("open mysql failed,", err)
return
}
Db = database
} func main() {
  //事务操作
conn, err := Db.Begin()
if err != nil {
return
}
  //插入数据
r, err := conn.Exec("insert into person(username, sex, email)values(?, ?, ?)", "stu001", "man", "stu01@qq.com")
if err != nil {
fmt.Println("exec failed, ", err)
return
}
id, err := r.LastInsertId()
if err != nil {
fmt.Println("exec failed, ", err)
    //回滚
     conn.Rollback()
return
} fmt.Println("insert succ:", id)
  //提交事务
conn.Commit()
}

二.查询数据库

package main

import (
"fmt" _ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
) type Person struct {
UserId int `db:"user_id"`
Username string `db:"username"`
Sex string `db:"sex"`
Email string `db:"email"`
} var Db *sqlx.DB func init() { database, err := sqlx.Open("mysql", "root:123@tcp(127.0.0.1:3306)/test")
if err != nil {
fmt.Println("open mysql failed,", err)
return
} Db = database
} func main() { var person []Person
err := Db.Select(&person, "select user_id, username, sex, email from person where user_id=?", 1)
if err != nil {
fmt.Println("exec failed, ", err)
return
} fmt.Println("select succ:", person)
}

三.修改数据库

package main

import (
"fmt" _ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
) type Person struct {
UserId int `db:"user_id"`
Username string `db:"username"`
Sex string `db:"sex"`
Email string `db:"email"`
} var Db *sqlx.DB func init() { database, err := sqlx.Open("mysql", "root:123@tcp(127.0.0.1:3306)/test")
if err != nil {
fmt.Println("open mysql failed,", err)
return
} Db = database
} func main() { _, err := Db.Exec("update person set username=? where user_id=?", "stu0003", 1)
if err != nil {
fmt.Println("exec failed, ", err)
return
} }

四.删除数据库

package main

import (
"fmt" _ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
) type Person struct {
UserId int `db:"user_id"`
Username string `db:"username"`
Sex string `db:"sex"`
Email string `db:"email"`
} var Db *sqlx.DB func init() { database, err := sqlx.Open("mysql", "root:123@tcp(127.0.0.1:3306)/test")
if err != nil {
fmt.Println("open mysql failed,", err)
return
} Db = database
} func main() { _, err := Db.Exec("delete from person where user_id=?", 1)
if err != nil {
fmt.Println("exec failed, ", err)
return
} fmt.Println("delete succ")
}
上一篇:Hitachi Content Platform学习


下一篇:Enterprise Solution 2.2 开发帮助文档集合