我正在使用 PostgreSQL C API,libpq。我需要能够将 PGresult*
中的值转换为它们在 Ruby 中的等效数据类型。我目前只是选择所有数据并使用 PQgetvalue()
,这为我提供了一个 char*
,我可以将其转换为 ruby 字符串。这很容易。但是有没有人可以分享从 char*
到 int
、float
或 double 的类型转换的例子
,根据PQftype()
返回的OID?
实际上,简而言之,我不知道如何解释 OID 和 the documentation似乎没有给出任何指示。我找到了 this page ,但这无助于理解如何使用此 OID 在 C API 中进行类型转换。我猜我可以从某处创建一个大的 switch 语句的常量列表?
最佳答案
我问了这个问题后找到了答案。基本上有一个名为 catalog/pg_type.h 的文件,以及 libpq-fe.h 和 postgres.h。您需要在包含 libpq-fe.h 和 postgres.h 之后包含,然后您可以访问 TEXTOID
、BOOLOID
、INT4OID
等定义.
#include <stdio.h>
#include <postgres.h>
#include <libpq-fe.h>
#include <catalog/pg_type.h>
// ... snip ...
if (PQgetisnull(result, row, col)) {
// value is NULL, nothing more to do
} else {
char * value = PQgetvalue(result, row, col);
int length = PQgetlength(result, row, col);
switch (PQftype(result, col)) {
case INT2OID:
case INT4OID:
case INT8OID:
// process value as an integer
break;
default:
// just default to a text representation
}
}
您需要查看 pg_type.h 中的所有 OID 以实际拥有一个广泛的列表,或者只是测试您通过基本 SELECT 't'::boolean
类型查询等返回的内容并构建只有当你需要一个新的类型支持时才打开开关。
关于c - 类型转换。我如何处理 C 中 libpq 中的 PostgreSQL OID 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12530449/