首页 > 解决方案 > PostgreSQL PqGetValue char 到 c 编程中的整数

问题描述

我对 C 语言中的 PostgreSQL 结果和整数有一点问题。所以我有一个具有这种结构的简单表:

ID(pk int) | 姓名(文字)| 值(整数)

1 | 苹果| 高分辨率照片| CLIPARTO 100

2 | 香蕉| 高分辨率照片| CLIPARTO 9

我使用这段代码:

PGconn *conn = PQconnectdb("user=un password=pw dbname=db hostaddr=1.2.3.4 port=5432");
res = PQexec(conn, "SELECT * FROM fruits WHERE name='banana'");
int *banan_count;
banana_count = (int)PQgetvalue(res, 0, 2);
printf ("Banana values : %u\n", banana_count);
PQclear(res);
do_exit(conn);

问题是,当我尝试使用“banana_count”打印出来时,我的结果不是“9”,但是当我打印出“PQgetvalue(res, 0, 2)”时,我得到了“9”,所以我想我有一个转换问题,但我找不到解决方案。所以我的问题是,如何在 C 编程语言中将 'PQgetvalue(res, 0, 2)' 转换为整数变量?(我使用 Ubuntu 18.04 并使用 gcc 编译我的 fruits.c)。

感谢您的支持和帮助。

标签: cpostgresqlubuntucharinteger

解决方案


在 C 中,从技术上讲,文本是一个字符数组,后跟一个空项。粗略地说,数组是一个指向已知大小的已分配内存的指针(语法可能有很大差异)。那么让我们看看代码。

PGconn *conn = PQconnectdb("user=un password=pw dbname=db hostaddr=1.2.3.4 port=5432");  //No doubts. It's your professional area.
res = PQexec(conn, "SELECT * FROM fruits WHERE name='banana'");  //same thing.
//int *banan_count; //Aside the typo (banana_count), you don't need a pointer to int! PQgetvalue returns a pointer to char (roughly equal to array of chars, roughly equal to text, you'll learn differences later). This array keeps ONE int value in text form.
int banana_count_2; //That's what you need: a single int value. Not a pointer.
//banana_count = (int)PQgetvalue(res, 0, 2); //Wrong: you take the pointer to char, convert it few times and assign to your int* pointer. Pointer becomes technically valid, but it points to first group of characters, reading them as an integer value (probably char1 + char2*256 + char3*65536 ... depending on your platform). Of course, actual integers are not represented in text form in computer memory, so you get an absurdly huge value (even '0' character has code 48).
banana_count_2 = atoi(PQgetvalue(res,0,2));  //PQgetvalue allocates memory by itself, so the char* it returns points to a valid, allocated memory area. We can say it's an array filled with null-terminated text line, and give this line to atoi();
printf ("Banana values : %u\n", banana_count_2);
PQclear(res);  //Good thing you didn't forget to unallocate the char array!
do_exit(conn);

推荐阅读