Go语言和PostgreSQL 9.4

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

Go language and PostgreSQL 9.4

问题

有一个支持 PostgreSQL 9.4 版本的 Go 语言的 PostgreSQL 库吗?PostgreSQL 9.4 支持 JSON 数据类型,我想知道它是否可以与 Go 语言一起使用?

谢谢。

英文:

Is there a PostgreSQL library for Go Language that supports PostgreSQL version 9.4.
PostgreSQL 9.4 has support for JSON datatype and was wondering if it can be used with Go Language?

Thanks.

答案1

得分: 2

是的,go pq应该支持PostgreSQL v9.4,并且它对JSON类型有基本的支持,将其作为字符串处理(似乎在v9.2中添加)。以下是示例代码:

// 创建表 foo (id SERIAL PRIMARY KEY, stuff json);
// 插入数据 INSERT INTO foo (stuff) VALUES ('{"x":123}');

type Foo struct {
  Id    int
  Stuff string
}

rows, err := db.Query("SELECT * FROM foo LIMIT 1") // TODO: 处理错误
defer rows.Close()
for rows.Next() {
  foo := Foo{}
  err = rows.Scan(&foo.Id, &foo.Stuff) // TODO: 处理错误
  // main.Foo{Id:1, Stuff:"{\"x\":123}"}
}

你可以对JSON字符串进行后处理,或者创建一个具有自定义"Scan"方法的自定义类型:

type Foo struct {
  Id    int
  Stuff MyStuff
}

func (e *MyStuff) Scan(value interface{}) error {
  // value应该是JSON字符串的[]byte。
  // 在这里进行你想要的任何操作...
}

希望对你有帮助!

英文:

Yes, the go pq library should support PostgreSQL v9.4 and it has basic support for JSON types as strings (which seem to have been added in v9.2).

// CREATE TABLE foo (id SERIAL PRIMARY KEY, stuff json);
// INSERT INTO foo (stuff) VALUES ('{"x":123}');

type Foo struct {
  Id    int,
  Stuff string,
}

rows, err := db.Query("SELECT * FROM foo LIMIT 1") // TODO: handle error
defer rows.Close()
for rows.Next() {
  foo := Foo{}
  err = rows.Scan(&foo.Id, &foo.Stuff) // TODO: handle error
  # main.Foo{Id:1, Stuff:"{\"x\":123}"}
}

You can either post-process the JSON string or create a custom type with a custom "Scan" method:

type Foo struct {
  Id    int,
  Stuff MyStuff,
}

func (e *MyStuff) Scan(value interface{}) error {
  // Value should be a []byte of the JSON string.
  // Do whatever you want with it here...
}

答案2

得分: 0

我使用 jmoiron/sqlx。对于任何不常见的数据类型,你可以实现 valuerscanner 接口。我已经使用这个包为使用 Postgis 的地理点实现了这些接口。

英文:

I use jmoiron/sqlx. For any not common datatypes you can implement the valuer and scanner interfaces. I have done this for geography points with Postgis using this package.

huangapple
  • 本文由 发表于 2015年4月15日 01:46:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/29634071.html
匿名

发表评论

匿名网友

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

确定