Golang Read and write MySQL example, using Mymysql driver

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Http://www.dotcoo.com/golang-mysql-mymysql

Golang, do a lot of systems are inseparable from the database, of course, the most commonly used or MySQL, today tested a connection MySQL database, ah. Cheer for Golang again.

This time use is Golang of Mymysql drive, haven't used MySQL for ages, still can't forget her.

Package main import ("FMT" "Database/sql" "github.com/ziutek/mymysql/godrv")//user structure type users struct {UID int username string Password String} func main () {//Set connection encoding godrv. Register ("SET NAMES UTF8")//Connect database db, err: = SQL. Open ("Mymysql", "tcp:127.0.0.1:3306*go/root/123456") if err! = Nil {panic (ERR)} defer db. Close ()//Insert Data stmt, err: = db.    Prepare ("INSERT into user values (null,?,?)") If err! = Nil {panic (err)} defer stmt. Close ()//SQL parameter result, err: = stmt. Exec ("cardamom", "dotcoo.com") if err! = Nil {panic (ERR)}//Gets the number of rows affected affect, err: = result. Rowsaffected () if err! = Nil {panic (err)} FMT. Printf ("%d\n", affect)//get the self-increment ID ID, err: = result. Lastinsertid () if err! = Nil {panic (err)} FMT. Printf ("%d\n", id)//query data rows, err: = db. Query ("SELECT * from user") IF Err! = Nil {panic (ERR)} defer rows. Close ()//Get user users: = []user{}//Read data for rows. Next () {User: = user{} ERR: = rows.               Scan (&user.uid, &user.username, &user.password) if nil! = Err {panic (err)} Users = Append (users, user)}//Displays user information for _, User: = Range users {fmt. Printf ("%d,%s,%s\n, User.uid, User.username, User.password)}}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.