Databases MYSQL
In this chapter, we will take a look at how to connect to a MYSQL Database.
For this, we will use the following packages:
"github.com/1nput0/go-crypto-tracker/assets"
_ "github.com/go-sql-driver/mysql"
To connect to our mysql database, i prefer to have a connection_url by passing the connection parameter to it. Preferably, by passing from an env file.
Example of an .env file with the connection_url:
SQL=root:root@tcp(127.0.0.1:3307)/DatabaseNameOpening a connection to the database:
// Load the connection url .env to a variable in Go
err := godotenv.Load()
if err != nil {
log.Fatalf("err loading: %v", err)
}
connection_url := os.Getenv("SQL")
// Connect to mysql and open a database
db, err := sql.Open("mysql", connection_url)
if err != nil {
panic(err.Error())
}
// Close the connection to the database at the end of the function
defer db.Close()Important things to know
In Go, the defer keyword allows a function to postpone the execution of a statement until the surrounding function has completed.
That means, with db.Close() we are only preparing closing our connection to the database once the main function was run.
In the next chapter, we will take a look at how to write something into the database.
Last updated