Posts

Showing posts with the label MySQL

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, ...