c - 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)。
感谢您的支持和帮助。
解决方案
在 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);
推荐阅读
- c# - 阻止控制台应用程序排队回调请求
- swiftui - navigationBarItems 将列表向右移动
- java - 使用模拟。尝试验证是否使用了我的方法
- python - 是否有 python 模块来指示 .py 是否正在运行?
- sharepoint - JQGrid 可以与 SharePoint 结果源 REST API 一起使用吗
- c# - 如何从正确转换为变量的列表框中获取值
- python - 无法将 numpy 模块导入 python 文件,但它适用于终端
- python - Tensorflow 已下载但未安装在 ubuntu 服务器上
- java - java selenium:想做一个采购机器人。我在页面上的 JavaScript 按钮有问题
- javascript - 清除材料设计下拉值会导致错误