Golang 连接MySql数据库使用方法

前端之家收集整理的这篇文章主要介绍了Golang 连接MySql数据库使用方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
https://blog.csdn.net/a19352226/article/details/50814900
package main

import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/MysqL"
)

var (
dbhostsip = "127.0.0.1:3306"//IP地址
dbusername = "root"//用户名
dbpassword = "123456"//密码
dbname = "Test"//表名
)

func main() {
db,err := sql.Open("MysqL","root:123456@tcp(127.0.0.1:3306)/Test?charset=utf8")
checkErr(err)
//插入数据
stmt,err := db.Prepare("INSERT userinfo SET username=?,departname=?,created=?")
checkErr(err)
res,err := stmt.Exec("码农","研发部门","2016-03-06")
checkErr(err)
id,err := res.LastInsertId()
checkErr(err)


fmt.Println(id)
//更新数据
stmt,err = db.Prepare("update userinfo set username=? where uid=?")
checkErr(err)


res,err = stmt.Exec("码农二代",id)
checkErr(err)

affect,err := res.RowsAffected()
checkErr(err)
fmt.Println(affect)


//查询数据
rows,err := db.Query("SELECT * FROM userinfo")
checkErr(err)
for rows.Next() {
var uid int
var username string
var department string
var created string
err = rows.Scan(&uid,&username,&department,&created)
checkErr(err)
fmt.Println(uid)
fmt.Println(username)
fmt.Println(department)
fmt.Println(created)
}

//删除数据
stmt,err = db.Prepare("delete from userinfo where uid=?")
checkErr(err)


res,err = stmt.Exec(id)
checkErr(err)


affect,err = res.RowsAffected()
checkErr(err)
fmt.Println(affect)
db.Close()
}
func checkErr(err error) {
if err != nil {
panic(err)
}
}

Go MysqL包地址:github.com/go-sql-driver/MysqL

本文代码参考:https://github.com/astaxie/build-web-application-with-golang

猜你在找的Go相关文章