golang连接MYSQL
一、安装驱动
go get -u github.com/go-sql-driver/mysql
二、代码编写
package main
import (
"database/sql"
"fmt"
"log"
_ "github.com/go-sql-driver/mysql"
)
func main() {
dbConnect, err := sql.Open("mysql", "root:111111@tcp(localhost:3306)/project?charset=utf8")
if err != nil {
log.Fatal(err)
return
}
//1、查询数据
rows, err := dbConnect.Query("select * from user_info ")
if err != nil {
log.Fatal(err)
return
}
if rows.Next() {
var id int
var username string
var create_time string
err := rows.Scan(&id, &username, &create_time)
if err != nil {
log.Fatal(err)
} else {
fmt.Printf("id: %v\n", id)
fmt.Printf("username: %v\n", username)
fmt.Printf("create_time: %v\n", create_time)
}
}
//2、插入数据
stmt, err := dbConnect.Prepare("insert user_info set username=?")
if err != nil {
log.Fatal(err)
return
}
res, err := stmt.Exec("ddxxhh3")
if err != nil {
log.Fatal(err)
return
}
fmt.Println(res.LastInsertId())
//3、更新数据
stmt2, err2 := dbConnect.Prepare("update user_info set username=? where id=? ")
if err2 != nil {
log.Fatal(err)
}
res2, err := stmt2.Exec("dxh123", 1)
if err != nil {
log.Fatal(err)
}
fmt.Println(res2.RowsAffected())
//4、删除数据
//TODO
}
三、结果如下
四、数据库连接格式
五、报错的情况
5.1 报错1:
main.go:8:2: no required module provides package github.com/go-sql-driver/mysql: go.mod file not found in current directory or any parent directory; see 'go help modules'
解决办法: 在当前目录下:
go mod init main.go
go get -u github.com/go-sql-driver/mysql