testpg2.pp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. Program testpg;
  2. { Demo program to test pascal connection with postgres database }
  3. { Translated from the testlibpq example program of PostGreSQL }
  4. Uses postgres,strings;
  5. Procedure exit_nicely(Conn : PPGconn);
  6. begin
  7. PQfinish(conn);
  8. halt(1);
  9. end;
  10. Var
  11. pghost,pgport,pgoptions,pgtty,dbname : Pchar;
  12. nFields,i : longint;
  13. conn : PPGConn;
  14. res : PPGresult;
  15. dummy : string;
  16. begin
  17. pghost := NiL; { host name of the backend server }
  18. pgport := NiL; { port of the backend server }
  19. pgoptions := NiL; { special options to start up the backend server }
  20. pgtty := NiL; { debugging tty for the backend server }
  21. if paramcount=1 then
  22. begin
  23. dummy:=paramstr(1)+#0;
  24. dbname:=@dummy[1];
  25. end
  26. else
  27. dbName := 'testdb';
  28. { make a connection to the database }
  29. conn := PQsetdb(pghost, pgport, pgoptions, pgtty, dbName);
  30. { check to see that the backend connection was successfully made }
  31. if (PQstatus(conn) = CONNECTION_BAD) then
  32. begin
  33. Writeln (stderr, 'Connection to database ',dbname,' failed.');
  34. Writeln (stderr, PQerrorMessage(conn));
  35. exit_nicely(conn);
  36. end;
  37. res := PQexec(conn, 'select * from email');
  38. if (PQresultStatus(res) <> PGRES_TUPLES_OK) then
  39. begin
  40. Writeln (stderr, 'select command failed.');
  41. PQclear(res);
  42. exit_nicely(conn);
  43. end;
  44. { first, print out the attribute names }
  45. nFields := PQnfields(res);
  46. Write ('|',PQfname(res, 0),space (4-strlen(PQfname(res, 0))) );
  47. Write ('|',PQfname(res, 1),space (20-strlen(PQfname(res, 1))) );
  48. Write ('|',PQfname(res, 2),space (40-strlen(PQfname(res, 2))) );
  49. writeln ('|');
  50. writeln ('+----+--------------------+----------------------------------------+');
  51. { next, print out the instances }
  52. for i := 0 to PQntuples(res)-1 do
  53. begin
  54. write('|',PQgetvalue(res, i, 0),space (4-strlen(PQgetvalue(res, i,0))));
  55. write('|',PQgetvalue(res, i, 1),space (20-strlen(PQgetvalue(res, i,1))));
  56. write('|',PQgetvalue(res, i, 2),space (40-strlen(PQgetvalue(res, i,2))));
  57. writeln ('|');
  58. end;
  59. PQclear(res);
  60. { close the connection to the database and cleanup }
  61. PQfinish(conn);
  62. end.