import("fmt"_"github.com/go-sql-driver/mysql""github.com/jmoiron/sqlx"_"github.com/jmoiron/sqlx""time")type Text struct{
Question string`db:"question"`
Answer string`db:"answer"`
OptionA string`db:"optionA"`
OptionB string`db:"optionB"`
OptionC string`db:"optionC"`
OptionD string`db:"optionD"`
No string`db:"no"`}funcconnect()*sqlx.DB {
db,_:= sqlx.Connect("mysql","root:@(localhost:3306)/test?charset=utf8mb4&parseTime=True&loc=Local")
db.SetConnMaxLifetime(time.Second *10)
db.SetMaxOpenConns(20)// 设置与数据库建立连接的最大数目
db.SetMaxIdleConns(10)// 设置连接池中的最大闲置连接数return db
}
查询语句
var db *sqlx.DB
funcmain(){
db =connect()Select()}funcSelect(){var text[] Text
sql:="select * from danxuan limit 5"_= db.Select(&text,sql)
fmt.Println(text)}
插入
// 插入数据var db *sqlx.DB
funcmain(){
db =connect()insert()}funcinsert(){
sqlStr :="insert into danxuan values (?,?,?,?,?,?,?)"_, err := db.Exec(sqlStr,10087,"你好","A.123","B.456","C.789","D.123","C")if err !=nil{
fmt.Printf("插入失败, err:%v\n", err)return}
fmt.Printf("插入成功 %d.\n")}
更新数据
var db *sqlx.DB
funcmain(){
db =connect()Update()}funcUpdate(){
sqlStr :="update danxuan set question=? where no = ?"
ret, err := db.Exec(sqlStr,"修改了呀",10087)if err !=nil{
fmt.Printf("更新失败, err:%v\n", err)return}
n,_:= ret.RowsAffected()// 操作影响的行数
fmt.Printf("update success, affected rows:%d\n", n)}
删除数据
var db *sqlx.DB
funcmain(){
db =connect()Delete()}funcDelete(){
sqlStr :="delete from danxuan where no = ?"
ret, err := db.Exec(sqlStr,10087)if err !=nil{
fmt.Printf("delete failed, err:%v\n", err)return}
n,_:= ret.RowsAffected()// 操作影响的行数
fmt.Printf("删除成功, affected rows:%d\n", n)}