1、需要导入驱动文件,需要执行
D:\GOPATH\src\GoData>go get
2、代码
// GoData project main.go package main import ( "database/sql" "fmt" _ "github.com/go-sql-driver/mysql" ) type user struct { t_id int t_username string t_password string t_mobile string t_registertime string t_lastpassword string t_question string t_answer string t_email string t_userType string } //select func queryRecord(db *sql.DB) { rows, err := db.Query("select * from t_user") checkErr(err) for rows.Next() { var u user err = rows.Scan(&u.t_username, &u.t_password, &u.t_registertime, &u.t_mobile, &u.t_lastpassword, &u.t_question, &u.t_answer, &u.t_email, &u.t_userType) u.showUser() } } //insert func insertRecord(u user, db *sql.DB) { dbis, err := db.Prepare("insert t_user set t_username =?,t_password=?,t_mobile=?,t_email=?") checkErr(err) res, err := dbis.Exec(u.t_username, u.t_password, u.t_mobile, u.t_email) checkErr(err) id, err := res.LastInsertId() fmt.Println(id) checkErr(err) } //update func updateRecord(db *sql.DB) { rows, err := db.Query("select * from t_user where t_user.t_id=1") checkErr(err) var u user for rows.Next() { err = rows.Scan(&u.t_id, &u.t_username, &u.t_password, &u.t_registertime, &u.t_mobile, &u.t_lastpassword, &u.t_question, &u.t_answer, &u.t_email, &u.t_userType) } up, err := db.Prepare("update t_user set t_password=? where t_id=?") up.Exec("hello world", u.t_id) } func deleteRecord(db *sql.DB) { } func (u user) showUser() { fmt.Println(u.t_username) fmt.Println(u.t_password) fmt.Println(u.t_registertime) fmt.Println(u.t_mobile) fmt.Println(u.t_lastpassword) fmt.Println(u.t_question) fmt.Println(u.t_answer) fmt.Println(u.t_email) fmt.Println(u.t_userType) } func checkErr(err error) { if err != nil { err.Error() } } func main() { db, err := sql.Open("mysql", "root:bianbian@/wuzhi") checkErr(err) //queryRecord(db) //u := user{44, "comebady", "1", "2", "3", "4", "5", "6", "7", "8"} //insertRecord(u, db) updateRecord(db) }
执行速度确实比java快多了额。。
有疑问加站长微信联系(非本文作者)