1. go-sql-driver/mysql
2. CRUD 示例
// mysql_demo project main.go
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
func MysqlTest() {
db, err := sql.Open("mysql", "root:123456@tcp(127.0.0.1:3306)/ld")
if err != nil {
fmt.Println("connect to mysql failed!")
return
} else {
fmt.Println("connected")
}
defer db.Close()
err = db.Ping()
if err != nil {
panic(err.Error())
}
// select
sqlSelect := "select * from ld.pet"
statement, err := db.Prepare(sqlSelect)
if err != nil {
fmt.Println("prepare statement failed:", err.Error())
return
}
defer statement.Close()
rows, err := statement.Query()
if err != nil {
fmt.Println("query failed:", err.Error())
}
columns, err := rows.Columns()
if err != nil {
fmt.Println(err.Error())
return
}
fmt.Println(columns)
row := make([]sql.RawBytes, len(columns))
scanArgs := make([]interface{}, len(row))
for i := range row {
scanArgs[i] = &row[i]
}
for rows.Next() {
err := rows.Scan(scanArgs...)
if err != nil {
panic(err.Error())
}
// row
for pos, col := range row {
fmt.Println(columns[pos], ":", string(col))
}
fmt.Println()
}
// insert
sqlInsert := "insert into ld.pet values('kk', 'ld', \"2018-12-13\", \"2018-12-13 15:56:50\", \"2018-12-13 15:57:00\")"
statement_insert, err := db.Prepare(sqlInsert)
if err != nil {
panic(err.Error())
}
statement_insert.Exec()
statement_insert.Close()
// delete
sqlDelete := "delete from ld.pet where name = 'kk'"
statement_delete, err := db.Prepare(sqlDelete)
if err != nil {
panic(err.Error())
}
statement_delete.Exec()
statement_delete.Close()
// update
sqlUpdate := "update ld.pet set ower = 'caicai' where name = 'gg'"
statement_update, err := db.Prepare(sqlUpdate)
if err != nil {
panic(err.Error())
}
statement_update.Exec()
statement_update.Close()
}
func main() {
fmt.Println("Hello World!")
MysqlTest()
}