Operate MySQL databases using golang

Source: Internet
Author: User

MySQL is a very simple and practical database. Currently, it can be integrated with many programming languages. Although the go language is quite young, it seems that it will always be used to catch up with the trend. I just tried the go language to operate the MySQL database. It seems that the amount of code is much less than that of practical Java, which is quite cool.

1. Download the driver

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

2. Put this package in the code.google.com directory (it doesn't matter where it is stored, as long as you can let the program find it)

3. Compile 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)}}

According to my understanding, in the SQL. Open method, the first parameter is the driver, which is the package we just added. We just introduced it in, so the first line of import is the driver. The second parameter is prone to errors. The format is quite different from that written in Java. However, basically there is no error in writing according to the above format. Compared with JDBC, it writes the load driver and the database to a method, saving a lot of code.

This is just a simple attempt. If you have time, check whether complicated operations are supported.

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.