Server-Side Scripting/SQL Databases/Go MySQL

routes/lesson9.go
"   return result; }

func countryExists(country string) bool { database := "Temperature" query := ` SELECT EXISTS(       SELECT * FROM Countries        WHERE Country = ?) AS Count;`

rows := mysqlQuery(database, query, country) var count int rows.Next rows.Scan(&count) return count == 1 }

func insertCountry(country string, temperature string) { database := "Temperature" query := ` INSERT INTO Countries (Country, Temperature) VALUES(?, ?);` mysqlExec(database, query, country, temperature); }

func updateCountry(country string, temperature string) { database := "Temperature" query := ` UPDATE Countries SET Temperature = ? WHERE Country = ?;` mysqlExec(database, query, temperature, country); }

func deleteCountry(country string) { database := "Temperature" query := ` DELETE FROM Countries WHERE Country = ?;` mysqlExec(database, query, country); }

func mysqlQuery(database string, query string, parameters ...interface{}) *sql.Rows { db, err := sql.Open("mysql", "root:root@tcp(localhost:3306)/" + database) if err != nil { log.Fatal(err) }   defer db.Close

var result *sql.Rows if parameters == nil { result, err = db.Query(query) } else { result, err = db.Query(query, parameters...) }   if err != nil { log.Fatal(err) }

return result }

func mysqlExec(database string, query string, parameters ...interface{}) sql.Result { db, err := sql.Open("mysql", "root:root@tcp(localhost:3306)/" + database) if err != nil { log.Fatal(err) }   defer db.Close

var result sql.Result if parameters == nil { result, err = db.Exec(query) } else { result, err = db.Exec(query, parameters...) }   if err != nil { log.Fatal(err) }

return result }

Try It
See ../../Routes and Templates/Go to create a test environment.