go mysqldb
1.go 支持mysqldb
go get -u github.com/go-sql-driver/mysql
现在,我们将看看如何在 Go 中使用 MySQL。这里我们使用准备好的语句。这是处理 SQL 数据库的最佳方式。
require (
...
github.com/go-sql-driver/mysql v1.6.0 // indirect
...
)
2.数据库结构
2.1定义一个查询
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
type Orderstruct {
OrderNumberint
OrderDatestring
Statusstring
}
func PingDB(db *sql.DB) {
err := db.Ping()
ErrorCheck(err)
}
func ErrorCheck(errerror) {
if err !=nil {
panic(err.Error())
}
}
func main() {
// ...
db, e :=sql.Open("mysql", "db_user:db_pass@tcp(remotehostname:3306)/order")
// query all data
rows, e := db.Query("select order_number,Order_Date,status from orders where order_number=131824")
ErrorCheck(e)
// declare empty post variable
var order =Order{}
// iterate over rows
for rows.Next() {
e = rows.Scan(&order.OrderNumber, &order.OrderDate, &order.Status)
ErrorCheck(e)
fmt.Println(order)
}
}
2.2执行结果
go build testdb.go
2.3 插入
// INSERT INTO DB
// prepare
stmt, e := db.Prepare("insert into order(order_number, order_date, status) values (?, ?, ?)")
ErrorCheck(e)
//execute
res, e := stmt.Exec("1", now(), "createorder")
ErrorCheck(e)
id, e := res.LastInsertId()
ErrorCheck(e)
fmt.Println("Insert id", id)
2.4 更新
//Update db
stmt, e := db.Prepare("update order set status=? where order_number=?")
ErrorCheck(e)
// execute
res, e := stmt.Exec("OK", "1")
ErrorCheck(e)
a, e := res.RowsAffected()
ErrorCheck(e)
fmt.Println(a) // 1 表示更新成功,如果是0,需要查看数据库配置是否有update权限。
2.5 删除
// delete data
stmt, e := db.Prepare("delete from order where id=?")
ErrorCheck(e)
// delete 5th post
res, e := stmt.Exec("5")
ErrorCheck(e)
// affected rows
a, e := res.RowsAffected()
ErrorCheck(e)
fmt.Println(a) // 删除成功