I'm trying to insert a row into a MySQL table:
package main
import (
"strconv"
"io/ioutil"
"strings"
"os/exec"
"database/sql"
_ "github.com/go-sql-driver/mysql"
)
func main() {
temp_cpu := getCPUTemp() // returns float32
temp_gpu := getGPUTemp() // returns float64
db, err := sql.Open("mysql", "user:pass@/sysStats")
handleError(err)
_, err = db.Query("INSERT INTO temperatures (id, cpu, gpu, timestamp) VALUES (?, ?, ?, ?)", 1, temp_gpu, temp_cpu, time.Now())
handleError(err)
db.Close()
return
}
It builds successfully but when I run the resulting binary it just times out after a long time with a generic timeout error.
The table has the following schema:
+----------------+-----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------------+-----------+------+-----+---------+-------+
| idtemperatures | int(11) | NO | PRI | NULL | |
| cpu | float | YES | | NULL | |
| gpu | float | YES | | NULL | |
| timestamp | timestamp | YES | | NULL | |
+----------------+-----------+------+-----+---------+-------+
I am running this on the same server the MySQL instance is hosted and I can access the database with the user/password from the terminal.
Any help?
Thanks!
The id / primary key field in your db is called "idtemperatures"
and you used "id"
in your SQL statement.
Also since you're not executing a query (but an INSERT
), you should use the DB.Exec()
method to execute it. You should never use DB.Query()
to execute DML (Data Manipulation Language) statements.
You may get a timeout error if you can't connect to your database. Make sure it uses default protocol (TCP) and host (localhost:3306). Another reason may be because you used DB.Query()
to execute your SQL INSERT
statement, and DB.Query()
returns an *sql.Rows
value which holds a database connection until you close it with the Rows.Close()
method - which you never do; you didn't even store the returned db.Rows
value.
Also you should call db.Close()
as a deferred statement, right after the error check after opening it.
Corrected example:
db, err := sql.Open("mysql", "user:pass@/sysStats")
if err != nil {
fmt.Println("Failed to open DB:", err)
return
}
defer db.Close()
s := "INSERT INTO temperatures (idtemperatures, cpu, gpu, timestamp) VALUES (?, ?, ?, ?)"
res, err = db.Exec(s, 1, temp_gpu, temp_cpu, time.Now())
if err != nil {
fmt.Println("Failed to execute INSERT:", err)
} else {
n, err := res.RowsAffected()
fmt.Println("INSERT executed, rows affected: ", n, err)
}