package main
import (
"database/sql"
"fmt"
"log"
"os"
"github.com/joho/godotenv"
_ "github.com/go-sql-driver/mysql"
)
func main() {
// Load environment variables from .env file
err := godotenv.Load()
if err != nil {
log.Fatalf("Error loading .env file")
}
// Get database connection details from environment variables
dbUser := os.Getenv("DB_USER")
dbPassword := os.Getenv("DB_PASSWORD")
dbHost := os.Getenv("DB_HOST")
dbPort := os.Getenv("DB_PORT")
dbName := os.Getenv("DB_NAME")
// Create the data source name (DSN)
dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s", dbUser, dbPassword, dbHost, dbPort, dbName)
// Connect to MySQL
db, err := sql.Open("mysql", dsn)
if err != nil {
panic(err.Error())
}
defer db.Close()
// Check if connection is ok
err = db.Ping()
if err != nil {
panic(err.Error())
}
fmt.Println("Connected to the database")
}