1.下载第三方库
go get github.com/go-sql-driver/mysql
2.连接数据库
db, err := sql.Open("mysql", "username:password@/databases")#连接数据库
我通常写一个函数去判断err是否存在
func check_errr(err error){
if err != nil{
fmt.Print(err)
}
}
查询语句
rows, err := db.Query("select name,age from students ")#查询语句
defer rows.Close()
for rows.Next() {
var nmae string
var age int
err := rows.Scan(&name, &age)//查询与赋值 循环内可定义变量 重新赋值
check_errr(err)
}
插入语句
tx,_:=db.Begin()
tx.Exec("insert into students (id,name,age) values (?,?,?) ",1,"Lisa",12)
tx.Commit()
删除语句
tx.Exec("delete from students where id=3")
tx.Commit()
更新语句
tx.Exec("UPdate students set age=? where id=?",1999,8)
tx.Commit()