pq: 无效的输入语法,类型为双精度:”$1″,使用Golang

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

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.

huangapple
  • 本文由 发表于 2015年8月1日 01:21:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/31751784.html
匿名

发表评论

匿名网友

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

确定