Home > Backend Development > Golang > What's the Most Reliable Way to Connect to MySQL from Go?

What's the Most Reliable Way to Connect to MySQL from Go?

Susan Sarandon
Release: 2024-12-23 01:07:05
Original
123 people have browsed it

What's the Most Reliable Way to Connect to MySQL from Go?

Connecting to MySQL from Go: What's the Most Reliable Solution?

When working with MySQL databases in Go, it's crucial to choose a reliable and widely used driver. While there are multiple options available, the most recommended approach is to utilize drivers that implement the database/sql API.

Benefits of Database/SQL API:

  • Clean and efficient syntax: Adherence to the API ensures readable and maintainable code.
  • Easy portability: The API allows you to switch between drivers effortlessly without altering your business logic.

Recommended Drivers:

  • MyMySQL:

    • Import: import "github.com/ziutek/mymysql/godrv"
  • Go-MySQL-Driver:

    • Import: import "github.com/go-sql-driver/mysql"

These drivers are known for their stability, high performance, and ability to handle large connection loads without interruptions.

Connection and Querying:

Once you've imported the appropriate driver, connect to your MySQL database as follows:

MyMySQL:

import "database/sql"

func main() {
    // Assuming you have defined database, user, and password.
    con, err := sql.Open("mymysql", database+"/"+user+"/"+password)
    defer con.Close()
}
Copy after login

Go-MySQL-Driver:

import "database/sql"

func main() {
    // Assuming you have defined store as a type containing user, password, and database fields.
    con, err := sql.Open("mysql", store.user+":"+store.password+"@/"+store.database)
    defer con.Close()
}
Copy after login

You can perform queries using the following syntax:

Select One Row:

row := con.QueryRow("select mdpr, x, y, z from sometable where>
Copy after login

Select Multiple Rows:

rows, err := con.Query("select a, b from item where p1=? and p2=?", p1, p2)
Copy after login

Insert:

_, err = con.Exec("insert into tbl (id, mdpr, isok) values (?, ?, 1)", id, mdpr)
Copy after login

By following these recommendations, you'll benefit from the robustness and flexibility of Go's database/sql API.

The above is the detailed content of What's the Most Reliable Way to Connect to MySQL from Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template