Javaer to go MySQL operation

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

After degrees Niang, found that more commonly used Golang MySQL driver package has two mymysql and Go-sql-driver/mysql. Personally feel that the name Mymysql is not elegant. So I chose the go-sql-driver/mysql.

1, the installation of Go-sql-driver/mysql

Because Go-sql-driver/mysql belongs to a third-party package, we need to get to this package first.

Add the installation package to our $gopath through the system's Shell tool (command line).

go get github.com/go-sql-driver/mysql

Note here: Use the above command not only to configure the Golang environment, but also to configure the Git bin directory in the PATH environment variable.

2. Operation MySQL

    • Guide Package
import (    "database/sql"    _ "github.com/go-sql-driver/mysql")

Because we use the process, not directly to the go-sql-driver/mysql, but through the interface in the Database/sql to use the driver, this is the same as the idea of Java. So when we import the Go-sql-driver/mysql package, we use underscores as placeholders to tell Golang that the contents of this package will not be used directly.

Note:

If you import a package without using it, you will throw an error when building the program, such as imported and not Used:os, which follows the motto of Go: "No unnecessary code!" “。

The declaration of a variable, too, throws an error if you declare a variable without using the variable.

The presence of placeholders solves the problem of importing the package without explicitly using the package.

    • Establish a connection
db, err := sql.Open("mysql""用户名:密码@/数据库名?charset=utf8")

The open function returns two values, but if we need only the DB value, regardless of the error, you can use a placeholder:

db, _:= sql.Open("mysql""用户名:密码@/数据库名?charset=utf8")
    • Exec
_, err := db.Exec(sql)

The EXEC function can execute a SQL that does not return, such as delete, UPDATE, insert operations.

    • Prepare
      Preprocessing a broken-down method to process SQL
      Such as:

Increase:

err := db.Prepare(`INSERT user (user_name,user_age,user_sex) values (?,?,?)`)checkErr(errerr := stmt.Exec("tony"201)checkErr(errerr := res.LastInsertId()checkErr(err)

Modify:

errSET user_age=?,user_sex=? WHERE user_id=?`)checkErr(errerr := stmt.Exec(2121)checkErr(errerr := res.RowsAffected()checkErr(err)

Delete:

err := db.Prepare(`DELETE FROM user WHERE user_id=?`)checkErr(errerr := stmt.Exec(1)checkErr(errerr := res.RowsAffected()checkErr(err)
    • Query

The query returns more than one record.

    err := db.Query("select id,nickname from user")    iferr != nil {        fmt.Println(err.Error())    }    defer rows.Close()    for rows.Next() {        int        string        rows.Scan(&id, &nickname)        fmt.Println(nickname)    }    db.Close()
    • Queryrow
      The query returns a record.
 row: = Open ().    Queryrow ( "select Id,nickname from user where id=129986" ) var  ID int  var  nickname string  row. Scan (&id, &nickname)  

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.