Avatar ·

Recommended way to connect to MySQL from Go: drivers, connection pools and best practices

Hello everyone! I'm a beginner Go developer, switching from Python where everything was simple with SQLAlchemy. Now I'm writing a small REST API in Go (pure net/http) and I need to connect to MySQL.

\n\n

I've read several tutorials, but they contradict each other. Some use go-sql-driver/mysql, some use database/sql directly, and others recommend ORMs like GORM. I'm completely confused.

\n\n

Here's an example of my current code that I threw together, but it looks "hacky":

\n\n
package main\n\nimport (\n    "database/sql"\n    "fmt"\n    _ "github.com/go-sql-driver/mysql"\n)\n\nfunc main() {\n    db, err := sql.Open("mysql", "user:password@tcp(127.0.0.1:3306)/dbname")\n    if err != nil {\n        panic(err.Error())\n    }\n    defer db.Close()\n\n