MySQL Insert Float32 and Float64 Go

huangapple go评论83阅读模式
英文:

MySQL Insert Float32 and Float64 Go

问题

我正在尝试向MySQL表中插入一行数据:

package main

import (
    "strconv"
    "io/ioutil"
    "strings"
    "os/exec"
    "database/sql"
    _ "github.com/go-sql-driver/mysql"
)

func main() {
    temp_cpu := getCPUTemp() // 返回 float32
    temp_gpu := getGPUTemp() // 返回 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
}

它成功构建,但当我运行生成的二进制文件时,它在很长时间后超时,并显示一个通用的超时错误。

该表具有以下模式:

+----------------+-----------+------+-----+---------+-------+
| Field          | Type      | Null | Key | Default | Extra |
+----------------+-----------+------+-----+---------+-------+
| idtemperatures | int(11)   | NO   | PRI | NULL    |       |
| cpu            | float     | YES  |     | NULL    |       |
| gpu            | float     | YES  |     | NULL    |       |
| timestamp      | timestamp | YES  |     | NULL    |       |
+----------------+-----------+------+-----+---------+-------+

我在与MySQL实例托管的同一台服务器上运行此代码,并且可以在终端中使用用户/密码访问数据库。

有什么帮助吗?

谢谢!

英文:

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!

答案1

得分: 0

你的数据库中的id/主键字段被称为"idtemperatures",而你在SQL语句中使用了"id"。

另外,由于你执行的是一个"INSERT"语句而不是查询,你应该使用"DB.Exec()"方法来执行它。你永远不应该使用"DB.Query()"来执行DML(数据操作语言)语句。

如果无法连接到数据库,你可能会遇到超时错误。确保它使用默认的协议(TCP)和主机(localhost:3306)。另一个原因可能是因为你使用"DB.Query()"来执行SQL的"INSERT"语句,而"DB.Query()"返回一个"*sql.Rows"值,它会一直持有数据库连接,直到你使用"Rows.Close()"方法关闭它——而你从未这样做过;你甚至没有存储返回的"db.Rows"值。

此外,你应该在打开数据库后的错误检查之后,作为延迟语句调用"db.Close()"。

修正后的示例代码:

db, err := sql.Open("mysql", "user:pass@/sysStats")
if err != nil {
    fmt.Println("打开数据库失败:", 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("执行INSERT失败:", err)
} else {
    n, err := res.RowsAffected()
    fmt.Println("INSERT执行成功,受影响的行数:", n, err)
}
英文:

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)
}

huangapple
  • 本文由 发表于 2015年11月17日 15:15:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/33751165.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定