![]() |
VOOZH | about |
MySQL is an open-source relational database management system based on Structured Query Language(SQL). It is a relational database that organizes data into one or more tables in which data are related to each other.
Database Driver: A Database Driver implements a protocol for a database connection. The Driver is like an adapter that connects to a generic interface to a specific database.
Initial Setup:
Start MySQL server and install go MySQL driver with the following command.
go get -u github.com/go-sql-driver/mysql
Creating database object:
Create a database object with sql.Open. There no connection established with MySQL instead, it creates only a database object which can be used later.
db, err := sql.Open("mysql", "<user>:<password>@tcp(127.0.0.1:3306)/<database-name>")
Replace 3306 if not using MySQL on the default port.
Output:
Execute Database Query: A database query can be done with Exec() and Query().
1. Creating a Database Table with SQL query and Exec().
Output:
👁 Image2. Inserting a row into Database Table with SQL query in Query().
Output:
👁 Image3. Using SQL query in Query() to return all rows from the user table.
Output:
👁 Image