Go语言 之Go操作Mysql
package main import ( "database/sql" "fmt" _ "github.com/go-sql-driver/mysql" ) func main() { //打开数据库 db, err := sql.Open("mysql", "root:root@(127.0.0.1:3306)/test") if err != nil { fmt.Println(err) } //延迟关闭数据库 defer db.Close() //连接数据库 db.Ping() //获取所有数据 rows, _ := db.Query("select * from test where id > ?", 1) var id, name string for rows.Next() { rows.Scan(&id, &name) fmt.Println(id, name) } //获取一条数据 row := db.QueryRow("select * from test where id = ?", 5) row.Scan(&id, &name) fmt.Println(id, name) //预处理 stmt, _ := db.Prepare("insert into test (id, name) values (?, ?)") result, _ := stmt.Exec(10, "haha") insert_id, _ := result.LastInsertId() fmt.Println(insert_id) }