执行更新
要更改数据(执行一个insert,update或者delete),可以使用Prepare加Exec 的方法,最终返回的是:
对于Update、insert、Delete语句执行成功是返回值为该命令所影响的行数,如果影响的行数是0,则返回值就是0;
对于所有其他类型的语句,返回值为-1;
如果发生回滚,返回值也为-1;
删除
stmt, err := db.Prepare(`Delete FROM products where name = $1`)
if err != nil {
fmt.Println("Some amazing wrong happens in preparation for the deletion.")
return err
}
res, err := stmt.Exec(pname)
if err != nil {
fmt.Println("Some amazing wrong happens in execution for the deletion.")
return err
}
num, err := res.RowsAffected()
if err != nil {
fmt.Println("Some amazing wrong happens in the affected fo deletion.")
return err
}
fmt.Println("Successfully delete", num)
更新
stmt, err := db.Prepare("Update products set price = $2 where product_no = $1")
if err != nil {
fmt.Println("Some amazing wrong happens in preparation for the update.")
return err
}
defer stmt.Close()
res, err := stmt.Exec(pno, newValue)
if err != nil {
fmt.Println("Some amazing wrong happens in execution for the update.")
return err
}
num, err := res.RowsAffected()
if err != nil {
fmt.Println("Some amazing wrong happens in the affected fo update.")
return err
}
fmt.Println("Successfully update ", num)
插入
stmt, err := db.Prepare("Insert into products(Product_No,Name,Price) values($1,$2,$3)")
if err != nil {
fmt.Println("Some amazing wrong happens in preparation for the insert.")
return err
}
defer stmt.Close()
res, err := stmt.Exec(project.ProductNo, project.Name, project.Price)
if err != nil {
fmt.Println("Some amazing wrong happens in the process of doInsertOne.")
return err
}
num, err := res.RowsAffected()
if err != nil {
fmt.Println("Some amazing wrong happens in the affected fo deletion.")
return err
}
fmt.Println("Successfully add ", num)