无法使用C ++连接到PostgreSQL [英] Cannot connect to PostgreSQL using C++

查看:164
本文介绍了无法使用C ++连接到PostgreSQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在我的mac上运行PostgreSQL。 PostgreQL本身工作正常,我可以创建数据库和表和东西,但是当我尝试连接到PostgreSQL使用C ++与类似:

I am trying to run PostgreSQL on my mac. PostgreQL itself works fine and I can create database and table and stuff but when I try to connect to PostgreSQL using C++ with something like:

#include <stdio.h>
#include </Library/PostgreSQL/8.4/include/libpq-fe.h>
#include <string>

int     main() {
PGconn          *conn;
PGresult        *res;
int             rec_count;

conn = PQconnectdb("dbname=ljdata host=localhost user=dataman);

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


$ b

and compile with something like:

g++ -lpq db.cpp -o db

我得到错误
ld:没有为-lpq

I get the error ld: library not found for -lpq

找到库,如果我编译没有lpq,我得到

and if I compile without lpq, I get

Undefined symbols:
  "_PQclear", referenced from:
      _main in ccpjNCAU.o
      _main in ccpjNCAU.o"



我已经包含libpq-fe.h,应该不会工作?是否有人知道发生了什么问题?

I have already included the libpq-fe.h, shouldn't it work? Does anybody know what went wrong?

推荐答案

g ++找不到 pq library。您必须指定在哪里查找它,资本 -L

g++ can't find the pq library. You have to specify where to look for it, with a capital -L:

g++ -L/path/to/pq/lib -lpq db.cpp -o db

pq 是/path/to/pq/lib/libpq.a(或任何扩展名)

where pq is /path/to/pq/lib/libpq.a (or whatever the extension is)

以下是您可能想要执行的操作:

Here's what you probably want to do:


  1. 将include行更改为不包含路径。

  1. change the include line to not have the path.

#include "libpq-fe.h"


  • 在命令行中添加包含路径

  • Add the include path to the commandline

    g++ -I/Library/PostgreSQL/8.4/include db.cpp
    


  • 构建中介对象文件

  • Build intermediary object files

    g++ -I/Library/PostgreSQL/8.4/include db.cpp -c -o db.o
    


  • 将它们作为单独的步骤链接在一起

  • Link it together as a separate step

    g++ -L/Library/PostgreSQL/8.4/lib db.o -lpq
    


  • 使用 -g

    单独构建步骤:编译并链接:

    Put it all together, for two separate build steps: compile and link:

    g++ -I/Library/PostgreSQL/8.4/include db.cpp -c -g -o db.o
    g++ -L/Library/PostgreSQL/8.4/lib db.o -lpq -o db
    

    这篇关于无法使用C ++连接到PostgreSQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆