Golang Mysql 增删改查
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
func main() {
//连接数据库
db, err := sql.Open("mysql", "root:@tcp(127.0.0.1:3306)/gupiao?charset=utf8")
if err != nil {
panic(err)
}
//关闭数据库
defer db.Close()
//增加数据
stmt, err := db.Prepare(`INSERT student (name,age) values (?,?)`)
res, err := stmt.Exec("wangwu", 26)
id, err := res.LastInsertId()
fmt.Println("自增id=", id)
//修改数据
stmt, _ = db.Prepare(`UPDATE student SET age=? WHERE id=?`)
res, err = stmt.Exec(21, 5)
num, err := res.RowsAffected() //影响行数
fmt.Println(num)
//删除数据
stmt, err = db.Prepare(`DELETE FROM student WHERE id=?`)
res, err = stmt.Exec(5)
num, err = res.RowsAffected()
fmt.Println(num)
//查询数据
rows, err := db.Query("SELECT userId,userName,userAge,userSex FROM student")
for rows.Next() {
var userId int
var userName string
var userAge int
var userSex int
rows.Columns()
err = rows.Scan(&userId, &userName, &userAge, &userSex)
fmt.Println(userId)
fmt.Println(userName)
fmt.Println(userAge)
fmt.Println(userSex)
}
}
如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!
txttool.com 说一段 esp56物联 查询128 IP查询