How to get MySQL data using sql.Query() in golang

How to get MySQL data using sql.Query() in golang

Hello fellow coders…

This is my first golang post here on blogger, I had been learning it for last a few months and now developing my own hobby project.

Today I am going to share how to get data from MySQL table using sql.Query() function.

First thing is connecting to MySQL database, to do so, I have used a separate function.

func dbConn() (db *sql.DB) {
 db, err := sql.Open("mysql", "root:my_password@tcp(127.0.0.1:3306)/my_database")

 if err != nil {
  log.Println("Can not open database connection")
 }
 return db
}

And in my function where I need to connect with database, I use

db := dbConn()
defer db.Close()

Always remember to close the database connection.

And in this function, I am trying to get vehicle_ids from table. Here I have used a variable to hold the string query. It makes code more readable and clean.

Here db.Query() returns a pointer to all available MySQL rows, so we need to bring that pointer into data. We iterate through all the given results using vals.Next() method, and we need to scan the ID from this.
For ease of use I have used integer slice to hold data.

query := `SELECT vehicle_id FROM booking WHERE start_date > ? and start_date > ? 
          UNION 
          SELECT vehicle_id FROM booking WHERE end_date < ?`
     

 bookingCheck, err := db.Query(query, startDate, endDate, startDate) //

 if err != nil {
  log.Println("Couldnt fetch available vehicles from booking table", bookingCheck)
 }

 var vehicleID int

 availableVehicles := []int{}

 for bookingCheck.Next() {
  err := bookingCheck.Scan(&vehicleID)

  if err != nil {
   log.Println("Scaning vehicle IDs failed")
  }

  availableVehicles = append(availableVehicles, vehicleID)
 }

This returns a slice with available vehicle IDs, Eg : [1 2 3]
I will update this with more details soon. Happy Coding…

Written with StackEdit.

Comments

Popular posts from this blog

Youtube-dl cheatsheet

Git mistakes - 1

Docker Development - Mistakes 1