golang对mysql进行增删改查
Posted _雪辉_
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了golang对mysql进行增删改查相关的知识,希望对你有一定的参考价值。
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
func main()
db, err := sql.Open("mysql", "user:password@tcp(127.0.0.1:3306)/dbname")
if err != nil
panic(err.Error())
defer db.Close() // 增
stmt, err := db.Prepare("INSERT INTO users(name, age) VALUES(?, ?)")
if err != nil
panic(err.Error())
res, err := stmt.Exec("John", 23)
if err != nil
panic(err.Error())
lastId, err := res.LastInsertId()
if err != nil
panic(err.Error())
fmt.Println(lastId) // 改
stmt, err = db.Prepare("update users set name=? where id=?")
if err != nil
panic(err.Error())
res, err = stmt.Exec("John Doe", lastId)
if err != nil
panic(err.Error())
affect, err := res.RowsAffected()
if err != nil
panic(err.Error())
fmt.Println(affect) // 查
rows, err := db.Query("SELECT * FROM users")
if err != nil
panic(err.Error())
for rows.Next()
var id int
var name string
var age int
err = rows.Scan(&id, &name, &age)
if err != nil
panic(err.Error())
fmt.Println(id, name, age)
// 删
stmt, err = db.Prepare("DELETE FROM users where id=?")
if err != nil
panic(err.Error())
res, err = stmt.Exec(lastId)
if err != nil
panic(err.Error())
affect, err = res.RowsAffected()
if err != nil
panic(err.Error())
fmt.Println(affect)
以上是关于golang对mysql进行增删改查的主要内容,如果未能解决你的问题,请参考以下文章