英文:
pq: invalid input syntax for type double precision: "$1" with Golang
问题
我正在尝试在我的GO程序中向PostgreSQL数据库进行简单的INSERT操作。我有一个值为0的float64类型的数字,而我的数据库中的某一列需要接受double precision类型的值。我不知道我需要将这个数字转换成什么类型才能让数据库接受这个值。
英文:
I'm trying to do a simple INSERT
into a postgresql
database in my GO
program. I have the number 0
that is a float64
, I have a column in my database that expects double precision
. I have no idea what I need to convert the number to in order for the database to accept the value.
答案1
得分: 1
PostgreSQL驱动程序很好地处理将float64插入到double precision列中:
tmp=# \d test
表 "public.test"
列名 | 类型 | 修饰符
--------+------------------+-----------
v | double precision |
代码如下:
package main
import (
"database/sql"
"fmt"
_ "github.com/lib/pq"
"log"
)
func main() {
db, err := sql.Open("postgres", "user=alex dbname=tmp sslmode=disable")
if err != nil {
log.Fatal(err)
}
result, err := db.Exec("insert into test values ($1)", float64(0.5))
if err != nil {
log.Fatal(err)
}
fmt.Println(result)
}
然后:
tmp=# select * from test ;
v
-----
0.5
0.5
0.5
(3 行)
这个问题被投票降低了,因为显然你提供的问题描述“不足以”重现问题。我尝试了一下,但是如你所见,它是可以工作的。
英文:
The PostgreSQL driver handles insertion of float64 into double precision columns quite well:
tmp=# \d test
Table "public.test"
Column | Type | Modifiers
--------+------------------+-----------
v | double precision |
And code:
package main
import (
"database/sql"
"fmt"
_ "github.com/lib/pq"
"log"
)
func main() {
db, err := sql.Open("postgres", "user=alex dbname=tmp sslmode=disable")
if err != nil {
log.Fatal(err)
}
result, err := db.Exec("insert into test values ($1)", float64(0.5))
if err != nil {
log.Fatal(err)
}
fmt.Println(result)
}
And then:
tmp=# select * from test ;
v
-----
0.5
0.5
0.5
(3 rows)
The question was downvoted because obviously the problem description you provided is not enough to reproduce the issue. I've tried to follow but as you see it is working.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论