1.使用go的mysql扩展实现curd
1.前提条件根据表的结构创建一个结构体
type Student struct { Id int Uid int Suject string Scores int cate_id int }
1.查询单条数据
//查询单条数据 func SelectOne(db *sql.DB){ u:= Student{} err:=db.QueryRow("select id,uid from score where id=?",1).Scan(&u.Id,&u.Uid) if err != nil { fmt.Println("this is error") } fmt.Println(u) }
2.查询多条数据
//查询多条数据 func SelectAll(db *sql.DB){ u:=Student{} rows,err:=db.Query("select id,uid from score where id > 2") if err != nil { log.Fatal("is error") } for rows.Next(){ err=rows.Scan(&u.Id,&u.Uid) fmt.Print(u.Id) fmt.Print(" ") fmt.Println(u.Uid) } }
3.插入数据
//插入数据 func InsertData(db *sql.DB){ ret,err:=db.Exec("INSERT INTO score (uid,suject,scores,cate_id) VALUES (?,?,?,?)",13,"美术",100,9) if err != nil { fmt.Println("insert data fail") return } id,err:=ret.LastInsertId() fmt.Printf("insert success this id is %d",id) }
4.修改语句
//修改数据 func UpdateDate(db *sql.DB){ ret,err:=db.Exec("UPDATE score SET suject=?,cate_id=? where id=?","音乐",9,10) if err != nil { fmt.Printf("update data is error") return } n,err:=ret.RowsAffected() fmt.Printf("update data is success%d",n) }
5.删除语句
//删除数据 func DelData(db *sql.DB){ ret,err:=db.Exec("DELETE FROM score where id =?",10) if err != nil { fmt.Printf("delete data is error") return } n,err:=ret.RowsAffected() fmt.Printf("delete data is success this status is %d",n) }
住入口文件
func main(){ db,err:=sql.Open("mysql","root:root@tcp(127.0.0.1:3306)/test") if err != nil { fmt.Println(111) } defer db.Close() //单条数据 //SelectOne(db) //查询多条数据 //SelectAll(db) //InsertData(db) //UpdateDate(db) //DelData(db) }