Reading records from MySQL
In the previous recipe, we created an employee record in the MySQL database. Now, in this recipe, we will learn how we can read it by executing a SQL query.
How to do it…
- Install the github.com/go-sql-driver/mysqlandgithub.com/gorilla/muxpackages using thego getcommand, as follows:
$ go get github.com/go-sql-driver/mysql $ go get github.com/gorilla/mux
- Create read-record-mysql.gowhere we connect to the MySQL database, perform aSELECTquery to get all the employees from the database, iterate over the records, copy its value into the struct, add all of them to a list, and write it to an HTTP response stream, as follows:
package main
import 
(
  "database/sql" "encoding/json"
  "log"
  "net/http"
  "github.com/go-sql-driver/mysql"
  "github.com/gorilla/mux"
)
const 
(
  CONN_HOST = "localhost"
  CONN_PORT = "8080"
  DRIVER_NAME = "mysql"
  DATA_SOURCE_NAME = "root:password@/mydb"
)
var db *sql.DB
var connectionError error
func init() 
{
  db, connectionError = sql... 
                                             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
     
         
                 
                 
                 
                 
                 
                 
                 
                 
                 
        