title | keywords | description | |
---|---|---|---|
MySQL |
|
Connecting to a MySQL database. |
This project demonstrates how to connect to a MySQL database in a Go application using the Fiber framework.
Ensure you have the following installed:
- Golang
- Fiber package
- MySQL
- Go MySQL Driver
-
Clone the repository:
git clone https://github.com/gofiber/recipes.git cd recipes/mysql
-
Install dependencies:
go get
-
Set up your MySQL database and update the connection string in the code.
- Start the application:
go run main.go
Here is an example of how to connect to a MySQL database in a Fiber application:
package main
import (
"database/sql"
"log"
"github.com/gofiber/fiber/v2"
_ "github.com/go-sql-driver/mysql"
)
func main() {
// Database connection
dsn := "username:password@tcp(127.0.0.1:3306)/dbname"
db, err := sql.Open("mysql", dsn)
if err != nil {
log.Fatal(err)
}
defer db.Close()
// Fiber instance
app := fiber.New()
// Routes
app.Get("/", func(c *fiber.Ctx) error {
var greeting string
err := db.QueryRow("SELECT 'Hello, World!'").Scan(&greeting)
if err != nil {
return err
}
return c.SendString(greeting)
})
// Start server
log.Fatal(app.Listen(":3000"))
}