【问题标题】:PostgreSQL PqGetValue char to integer in c programmingPostgreSQL PqGetValue char 到 c 编程中的整数
【发布时间】:2020-06-05 02:34:59
【问题描述】:

我对 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)。

感谢您的支持和帮助。

【问题讨论】:

  • atoi函数。 printf("%d\n", atoi(PQgetvalue(res,0,2)));
  • 感谢您的快速回答,我尝试了 atoi 但遗憾的是它也无法正常工作。明天我会尝试“rb_cstr_to_inum”,也许它会起作用。 :)
  • 嗯,它应该确实有效。如果您准确地展示了您尝试过的内容,那么有人会发现错误

标签: c postgresql ubuntu char integer


【解决方案1】:

在 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);

【讨论】:

  • 谢谢你的详细解释 :) 确实我需要学习很多,所以再次感谢你。
  • 另外,printf ("Banana values : %u\n", banana_count); 打印了指针本身(内存地址),它不依赖于值(它是存储它的内存单元的数量)。 printf ("Banana values : %u\n", *banana_count); 将打印出“荒谬的巨大价值”。这就是我忘记提及的。
  • 我明白了,再次感谢你,这是真的,我已经获得了很多次巨大的价值。
猜你喜欢
  • 2017-10-08
  • 1970-01-01
  • 2013-06-02
  • 1970-01-01
  • 2010-12-28
  • 2013-09-13
  • 2014-11-01
  • 2016-03-11
  • 1970-01-01
相关资源
最近更新 更多