golang mysql基本操作
阿新 • • 發佈:2018-12-15
package main import ( _ "github.com/go-sql-driver/mysql" "database/sql" "fmt" ) func main() { db, err := sql.Open("mysql", "username:[email protected](127.0.0.1:3306)/db?charset=utf8") checkErr(err) defer db.Close() uname := "username" // query stmt, err := db.Prepare("SELECT USER_NAME, `PASSWORD` FROM db.TAPP_USER WHERE USER_NAME = ?") checkErr(err) rows, err := stmt.Query(uname) checkErr(err) for rows.Next() { var username string var password string err = rows.Scan(&username, &password) checkErr(err) fmt.Println(username) fmt.Println(password) } // update newPwd := "newUserPwd" stmt, err = db.Prepare("UPDATE db.TAPP_USER SET `PASSWORD` = ? WHERE USER_NAME = ?") checkErr(err) res, err := stmt.Exec(newPwd, uname) checkErr(err) affect, err := res.RowsAffected() checkErr(err) fmt.Println(affect) // query stmt, err = db.Prepare("SELECT USER_NAME, `PASSWORD` FROM db.TAPP_USER WHERE USER_NAME = ?") checkErr(err) rows, err = stmt.Query(uname) checkErr(err) for rows.Next() { var username string var password string err = rows.Scan(&username, &password) checkErr(err) fmt.Println(username) fmt.Println(password) } } func checkErr(err error) { if err != nil { fmt.Println(err.Error()) } }