CREATE TABLE `userinfo` ( `uid` INT(10) NOT NULL AUTO_INCREMENT, `username` VARCHAR(64) NULL DEFAULT NULL, `departname` VARCHAR(64) NULL DEFAULT NULL, `created` DATE NULL DEFAULT NULL, PRIMARY KEY (`uid`) ) CREATE TABLE `userdetail` ( `uid` INT(10) NOT NULL DEFAULT '0', `intro` TEXT NULL, `profile` TEXT NULL, PRIMARY KEY (`uid`) )
https://github.com/Go-SQL-Driver/MySQL
package main import ( "database/sql" "fmt" _ "github.com/Go-Sql-Driver/MySql" "log" "time" ) func main() { db, err := sql.Open("mysql", "root:123456@tcp(localhost:3306)/test?charset=utf8") checkErr(err) //插入数据 stmt, err := db.Prepare("insert userinfo set username=?,departname=?,created=?") checkErr(err) res, err := stmt.Exec("nilz", "研发部门", time.Now()) checkErr(err) id, err := res.LastInsertId() checkErr(err) fmt.Println("id:", id) //更新数据 stmt, err = db.Prepare("update userinfo set username=? where uid=?") checkErr(err) res, err = stmt.Exec("nilzupdate", id) checkErr(err) affect, err := res.RowsAffected() checkErr(err) fmt.Println(affect) //查询数据 rows, err := db.Query("select * from userinfo") checkErr(err) for rows.Next() { var uid int var username string var department string var created string err = rows.Scan(&uid, &username, &department, &created) checkErr(err) fmt.Println(uid) fmt.Println(username) fmt.Println(department) fmt.Println(created) } //删除数据 stmt, err = db.Prepare("delete from userinfo where uid=?") checkErr(err) res, err = stmt.Exec(id) checkErr(err) affect, err = res.RowsAffected() checkErr(err) fmt.Println(affect) db.Close() } func checkErr(err error) { if err != nil { fmt.Println(err) log.Fatal(err) } }
这里的github.com/Go-Sql-Driver/MySql是cmd go get github.com/Go-Sql-Driver/MySql到gopath中的 首先需要安装git
执行结果