【发布时间】:2017-03-24 08:50:04
【问题描述】:
我正在尝试将在 Windows 上运行的 C 脚本连接到我的 Postgresql 数据库。
目前,我在一个网站上得到了这个脚本:
#include <stdio.h>
#include "libpq-fe.h"
#include <string>
#include <stdlib.h>
int main() {
PGconn *conn;
PGresult *res;
int rec_count;
int row;
int col;
conn = PQconnectdb("dbname=ljdata host=localhost user=dataman password=supersecret");
if (PQstatus(conn) == CONNECTION_BAD) {
puts("We were unable to connect to the database");
exit(0);
}
res = PQexec(conn,
"update people set phonenumber=\'5055559999\' where id=3");
res = PQexec(conn,
"select lastname,firstname,phonenumber from people order by id");
if (PQresultStatus(res) != PGRES_TUPLES_OK) {
puts("We did not get any data!");
exit(0);
}
rec_count = PQntuples(res);
printf("We received %d records.\n", rec_count);
puts("==========================");
for (row=0; row<rec_count; row++) {
for (col=0; col<3; col++) {
printf("%s\t", PQgetvalue(res, row, col));
}
puts("");
}
puts("==========================");
PQclear(res);
PQfinish(conn);
return 0;
}
我复制了 libpq-fe.h、postgres_ext.c 和 pg_config_ext.c 以避免错误。
现在我遇到了所有这些错误:
- 未定义对“PQconnectdb”的引用
- 未定义对“PQresultStatus”的引用
- ...
所以显然我没有包含我需要的所有功能的 file.c,但我找不到它。
我在另一个论坛上看到我需要创建一个 makefile 来告诉编译器使用 libpq.dll(我有这个文件)但我不知道这样做。
我怎样才能使它工作?
编辑
所以现在当我尝试这样编译它时:
gcc -I "C:\Program Files\PostgreSQL\9.6\include" -L "C:\Program Files\PostgreSQL\9.6\lib" test.c -lpq
我得到了错误:
C:\Program Files\PostgreSQL\9.6\lib/libpq.dll: file not recognized: File format not recognized
collect2.exe: error: ld returned 1 exit status
我认为它已接近最终解决方案。
根据我的研究,我发现 libpq.dll 是 32 位的,但我的环境是 64 位的。这有什么改变吗?
编辑 2
编译现在可以正常使用这一行了:
gcc -m64 -I "C:\Program Files\PostgreSQL\9.6\include" -L "C:\Program Files\PostgreSQL\9.6\lib" test.c -lpq -o test.exe
但是当我双击 .exe 时出现以下错误:
“无法启动程序,因为缺少 LIBPQ.dll”
所以这显然意味着我必须将 libpq.dll 与可能指向 Program Files/PG/9.6/lib 的链接链接起来。
这里的问题是我想构建一个独立的 .exe,它可能嵌入 Postgresql 库以正常工作,即使计算机目标没有安装 Postgresql
(这是可能的,例如在 Java 中,当我们构建一个包含所有外部库复制的 Jar 时)
在 C 中可能吗?我想我需要调整我的编译行,但我没有找到可以添加哪个参数来在 .exe 中导入所有需要的库
【问题讨论】:
-
你不需要 C 文件,你只需要像这样在链接器中包含 Postgres 库:
-lpq。 -
因为我是windows,所以必须用mingw编译。当我输入“g++ -lpq test.c”时,出现以下错误:“找不到 -lpq”
-
你也在编译那些 .c 文件吗?例如,如果您使用 gcc,
gcc main.c postgres_ext.c pg_config_ext.c -o ouput -
对不起,我弄错了,那些文件是头文件(.h)
标签: c windows postgresql