package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
func CheckError(err error) {
if err != nil {
panic(err.Error())
}
}
func main() {
//实现mysql的增删改查
fmt.Println("start")
con, err := sql.Open("mysql", "root:123456@/test?charset=utf8")
CheckError(err)
defer con.Close()
err = con.Ping()
CheckError(err)
//插入或者更新
sql1 := "insert into country(name,user_age)values(?,?);"
smt, err := con.Prepare(sql1)
CheckError(err)
defer smt.Close()
_, err = smt.Exec("tom", 29)
CheckError(err)
sql1 = "update country set name=? where id=1"
smt, err = con.Prepare(sql1)
CheckError(err)
_, err = smt.Exec("tim")
CheckError(err)
//获取数据
select_sql := "select * from country limit 10"
rows, err := con.Query(select_sql)
CheckError(err)
columns, err := rows.Columns()
fmt.Println(columns, len(columns))
values := make([]sql.RawBytes, len(columns))
scanArg := make([]interface{}, len(columns))
for i := range values {
scanArg[i] = &values[i]
}
for rows.Next() {
err = rows.Scan(scanArg...)
CheckError(err)
var value string
for i, col := range values {
if col == nil {
value = "NULL"
} else {
value = string(col)
}
fmt.Println(columns[i], "=", value)
}
}
}
golang的mysql操作
最新推荐文章于 2022-08-05 19:03:32 发布