Golang working with MySQL database

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

MySQL is a simple and useful database for getting started, and it can be combined with many programming languages. Although the go language is very young, but it seems to catch up with the trend will always have it. Just tried the next go language operation MySQL database, seemingly a lot less code than practical Java, very cool.

1. Download driver

Https://github.com/go-sql-driver/mysql

2. Place the package in the Code.google.com directory (where it doesn't matter, as long as you can get the program to find it)

3. Write a simple test program

Package Mainimport (_ "Code.google.com/mysql" "Database/sql" "FMT") func main () {//format "user:password@tcp (ip:port)/ Database "db, err: = SQL. Open ("MySQL", "Root: @tcp (127.0.0.1:3306)/test?charset=utf8") if err! = Nil {fmt. PRINTLN ("Error in Connect", err. Error ()) return}fmt. Println ("Connect OK") rows, err: = db. Query ("Select * from Stu") if err! = Nil {fmt. PRINTLN ("Error in select", Err. Error ()) return}if rows = = Nil {fmt. Println ("Rows is nil") return}for rows. Next () {var u, p stringe: = rows. Scan (&u, &p) if E! = nil {fmt. Println ("Err", E.error ()) return}fmt. Println (U, "", p)}}

As I understand it, SQL. In the Open method, the first parameter is the drive, which is the package we just added. We just introduced it, so the first line of import is the driver. Error-prone is the second parameter, the format and Java write the difference is quite big, but basically in accordance with the above format is not wrong. Compared to JDBC, the load driver and connection database are written in a single method, saving a lot of code.

This is just a little bit of a try, if there is time, to see more complicated operation is not also supported.

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.