[转]VC代码连接PostgreSql

      好。。在连接postgresql时,如果用ADO或是ODBC连接的话,资料就很多了,其实用代码也没多少。只是要注意的一些小细节会折磨人很久噢。。       下载postgresql就不说了,我用的是8.0版本。在安装时,如果是软件运行的目标机器,那么,就不用选择develop选项中的组件了,如果是开发的话,你就保证其中的“include”和“lib”文件夹的组件被选中(安装过程一定要注意,因为界面会弹出很多对话框的),如果你是第二次在同一台机器上安装多次的话,有可能会产生“the user have already existed”那么可以使用net user postgres /delete (如果选择的用户名是postgres的话);

      VC开发时(其他环境其实时一样的,而且类似的例子多得要命),首先在postgresql的安装目录下的include中找到 libpq-fe.h的头文件,在lib中会有一个名为“MS”的文件夹,这个非常重要,如果找不到。那么说明安装时的开发组件没有装全,在这个文件夹中有一个“libpq.lib”的库文件这个是在windows环境下用到的库文件,不要将其中的“libpq.a”这个linux下的库添加到工程中来,这样会导致memory crash的(而且编译时不会出错,系统还认其中对数据库操作的函数噢,不可小视!)。。对,接下来就把这两个文件拷贝到当前工作目录里,或者将路径设置好就行了,可能还要拷贝进来一个头文件,编译时会提示的(小case了),可以了。。

接下来,就可以进行数据库的连接。查询了,查询时注意字符串的细节问题。。

#include <libpq-fe.h>

 

 char              * string_for_query;;

 PGconn        *conn_pointer;

 PGresult       *result;

 char       *pghost,

              *pgport,

              *pgoptions,

              *pgtty;

              *dbName;

              *username;

              *password;

 pghost       =     “localhost”;      //IP address string is also ok       

 pgport        =     ”5432″;             

 pgoptions   =      NULL;          

 pgtty          =      NULL;              

 dbName     =      “student_db”;    

 username   =      “postgres”;      //postegres is the username that

                                                //set when installed postgresql it can be read

                                               // from registry

  password   =        “11111″    //set when insalled cannot get directly

  int main()

  {

      Conn_pointer=PQsetdbLogin(pghost, pgport, pgoptions, pgtty, dbName, username, password);
      if (PQstatus(conn) == CONNECTION_BAD)

             {

                      printf(“cannot connect to the database! “);

return -1;

}

string_for_query=”select * from student”;//SQL query

……

……

}

一条评论 »

  1. 1 said,

    六月 30, 2010 at 10:36 上午

    谢谢,到网上找了一些,就你这个能跑起来,但还是有些错误,
    需要添加lib,和dll文件
    完整代码,VC++6.0
    #include “stdafx.h”
    #include

    char * string_for_query;;
    PGconn *Conn_pointer;
    PGresult *result;

    char* pghost = “localhost”; //IP address string is also ok
    char* pgport =”5432″;
    char* pgoptions =NULL;
    char* pgtty = NULL;
    char* dbName = “school”;
    char* username = “postgres”; //postegres is the username that
    char* password = “123456″ ;//set when insalled cannot get directly

    #pragma comment(lib,”C:\\Program Files\\PostgreSQL\\8.3\\lib\\libpq.lib”)
    int main()
    {
    Conn_pointer=PQsetdbLogin(pghost, pgport, pgoptions, pgtty, dbName, username, password);
    if (PQstatus(Conn_pointer) == CONNECTION_BAD)
    {
    printf(“cannot connect to the database!\n”);
    return -1;
    }
    printf (“Connect to database seccess\n”);
    return 0;
    }

RSS feed for comments on this post · TrackBack URL

发表评论

You must be logged in to post a comment.