建一个简单的test表
CREATE TABLE `test` ( `a` int(11) NOT NULL AUTO_INCREMENT, `b` int(11) DEFAULT NULL, PRIMARY KEY (`a`) ) ENGINE=InnoDB AUTO_INCREMENT=157
package main import ( "database/sql" "fmt" _ "github.com/go-sql-driver/mysql" ) func main() { db, err := sql.Open("mysql", "root:@tcp(127.0.0.1:3306)/test?charset=utf8") if err != nil { panic(err.Error()) } defer db.Close() rows, _ := fetchRows(db, "SELECT * FROM test") for _, v := range *rows { fmt.Println(v["a"], v["b"]) } fmt.Println(insert(db, "INSERT INTO test( b ) VALUES( ? )", 1)) row, _ := fetchRow(db, "SELECT * FROM test where a = ?", 1) fmt.Println(*row) } //插入 func insert(db *sql.DB, sqlstr string, args ...interface{}) (int64, error) { stmtIns, err := db.Prepare(sqlstr) if err != nil { panic(err.Error()) } defer stmtIns.Close() result, err := stmtIns.Exec(args...) if err != nil { panic(err.Error()) } return result.LastInsertId() } //修改和删除 func exec(db *sql.DB, sqlstr string, args ...interface{}) (int64, error) { stmtIns, err := db.Prepare(sqlstr) if err != nil { panic(err.Error()) } defer stmtIns.Close() result, err := stmtIns.Exec(args...) if err != nil { panic(err.Error()) } return result.RowsAffected() } //取一行数据,注意这类取出来的结果都是string func fetchRow(db *sql.DB, sqlstr string, args ...interface{}) (*map[string]string, error) { stmtOut, err := db.Prepare(sqlstr) if err != nil { panic(err.Error()) } defer stmtOut.Close() rows, err := stmtOut.Query(args...) if err != nil { panic(err.Error()) } columns, err := rows.Columns() if err != nil { panic(err.Error()) } values := make([]sql.RawBytes, len(columns)) scanArgs := make([]interface{}, len(values)) ret := make(map[string]string, len(scanArgs)) for i := range values { scanArgs[i] = &values[i] } for rows.Next() { err = rows.Scan(scanArgs...) if err != nil { panic(err.Error()) } var value string for i, col := range values { if col == nil { value = "NULL" } else { value = string(col) } ret[columns[i]] = value } break //get the first row only } return &ret, nil } //取多行,<span style="font-family: Arial, Helvetica, sans-serif;">注意这类取出来的结果都是string </span> func fetchRows(db *sql.DB, sqlstr string, args ...interface{}) (*[]map[string]string, error) { stmtOut, err := db.Prepare(sqlstr) if err != nil { panic(err.Error()) } defer stmtOut.Close() rows, err := stmtOut.Query(args...) if err != nil { panic(err.Error()) } columns, err := rows.Columns() if err != nil { panic(err.Error()) } values := make([]sql.RawBytes, len(columns)) scanArgs := make([]interface{}, len(values)) ret := make([]map[string]string, 0) for i := range values { scanArgs[i] = &values[i] } for rows.Next() { err = rows.Scan(scanArgs...) if err != nil { panic(err.Error()) } var value string vmap := make(map[string]string, len(scanArgs)) for i, col := range values { if col == nil { value = "NULL" } else { value = string(col) } vmap[columns[i]] = value } ret = append(ret, vmap) } return &ret, nil }
有疑问加站长微信联系(非本文作者)