1, establish the database name: go_test_db
2, the table name is:userinfo
Field:
UID int
username varchar
language varchar
created varchar
3, the database operation
Package main import ("Database/sql" "Fmt" _ "Github.com/go-sql-driver/mysql") func main () {db, err: = sq L.open ("MySQL", "Go:[email protected]/go_test_db?charset=utf8")//parse SQL here. Parameter parsing for open pass://db,err: = sql. Open ("MySQL", "Login name: Login password @/database name Charset=utf8") Checkerr (ERR)//Insert Data stmt, err: = db. Prepare ("INSERT userinfo SET username=?,language =?,created=?") Checkerr (Err) res, err: = stmt. Exec ("Haojieli", "Java", "2016-07-12") Checkerr (ERR) ID, err: = Res. Lastinsertid () Checkerr (err) fmt. Println ("Get Add successful value=", id) <br>//Update data stmt, err = db. Prepare ("Update userinfo set username=?") where uid=? ") Checkerr (Err) res, err = stmt. Exec ("Update later", ID) checkerr (ERR) affect, err: = Res. Rowsaffected () Checkerr (err) fmt. PRINTLN ("Update the currently added data to 1 is the update success.") Value = ", affect)//query data rows, err: = db. Query ("SELECT * from UserInfo")///This example is to query the UserInfo table all the data, paging changes the MySQL statement can be, page Statement example: SELECT * from UserInfo limit 0,5 (Limit analysisSee another article) Checkerr (err) fmt. PRINTLN ("Query all UserInfo--------------------start") for rows. Next () {var uid int var username string var department string var created string err = Rows. Scan (&uid, &username, &language, &created) checkerr (err) fmt. Print (uid, "|") Fmt. Print (username, "|") Fmt. Print (Language, "|") Fmt. Println (created)} FMT. PRINTLN ("Query all UserInfo--------------------end") <br>//delete data stmt, err = db. Prepare ("Delete from userinfo where uid=?") Checkerr (Err) res, err = stmt. Exec (id-1) checkerr (err) fmt. Println ("Delete the previous data for the Add ID, 1 is the successful deletion.") Value = ", affect) db. Close ()}<br><br>//checks if there is an error in the Func Checkerr (err error) {if err! = Nil {panic (err)//panic is to get to the true meaning of the errors }}
This is the end of the blog, thank you for watching, I hope to help readers, if you have any comments and suggestions please comment on the message ...
====== wish you a happy life ======
Go language Add, delete, change, check operation of MySQL database