写一段代码:使用golang对mysql进行增删改查
时间: 2023-03-09 10:26:45 浏览: 291
基于beego简单几行代码实现对mysql数据库的增删改查操作
5星 · 资源好评率100%
package mainimport (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)func main() {
db, err := sql.Open("mysql", "user:password@tcp(127.0.0.1:3306)/dbname")
if err != nil {
panic(err.Error())
}
defer db.Close() // 增
stmt, err := db.Prepare("INSERT INTO users(name, age) VALUES(?, ?)")
if err != nil {
panic(err.Error())
}
res, err := stmt.Exec("John", 23)
if err != nil {
panic(err.Error())
}
lastId, err := res.LastInsertId()
if err != nil {
panic(err.Error())
}
fmt.Println(lastId) // 改
stmt, err = db.Prepare("update users set name=? where id=?")
if err != nil {
panic(err.Error())
}
res, err = stmt.Exec("John Doe", lastId)
if err != nil {
panic(err.Error())
}
affect, err := res.RowsAffected()
if err != nil {
panic(err.Error())
}
fmt.Println(affect) // 查
rows, err := db.Query("SELECT * FROM users")
if err != nil {
panic(err.Error())
}
for rows.Next() {
var id int
var name string
var age int
err = rows.Scan(&id, &name, &age)
if err != nil {
panic(err.Error())
}
fmt.Println(id, name, age)
} // 删
stmt, err = db.Prepare("DELETE FROM users where id=?")
if err != nil {
panic(err.Error())
}
res, err = stmt.Exec(lastId)
if err != nil {
panic(err.Error())
}
affect, err = res.RowsAffected()
if err != nil {
panic(err.Error())
}
fmt.Println(affect)
}
阅读全文