MySQL Example
This project demonstrates how to connect to a MySQL database in a Go application using the Fiber framework.
Prerequisites
Ensure you have the following installed:
- Golang
- Fiber package
- MySQL
- Go MySQL Driver
Setup
-
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.
Running the Application
- Start the application:
go run main.go
Example
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"))
}