Guest User

Untitled

a guest
Apr 3rd, 2018
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.10 KB | None | 0 0
  1. // program pyta uzytkownika o dane do wpisania
  2.  
  3. #include <stdlib.h>
  4. #include <libpq-fe.h>
  5. #include <stdio.h>
  6.  
  7. void doSQL(PGconn *conn, char *command)
  8. {
  9. PGresult *result;
  10.  
  11. printf("%s\n", command);
  12.  
  13. result = PQexec(conn, command);
  14. printf("status is : %s\n", PQresStatus(PQresultStatus(result)));
  15. printf("#rows affected: %s\n", PQcmdTuples(result));
  16. printf("result message: %s\n", PQresultErrorMessage(result));
  17.  
  18. switch(PQresultStatus(result)) {
  19. case PGRES_TUPLES_OK:
  20. {
  21. int n = 0, r = 0;
  22. int nrows = PQntuples(result);
  23. int nfields = PQnfields(result);
  24. printf("number of rows returned = %d\n", nrows);
  25. printf("number of fields returned = %d\n", nfields);
  26. for(r = 0; r < nrows; r++) {
  27. for(n = 0; n < nfields; n++)
  28. printf(" %s = %s", PQfname(result, n),PQgetvalue(result,r,n));
  29. printf("\n");
  30. }
  31. }
  32. }
  33. PQclear(result);
  34. }
  35.  
  36. int main()
  37. {
  38. PGresult *result;
  39. PGconn *conn;
  40. char odp, name[20], zapytanie[200];
  41. int value;
  42. conn = PQconnectdb("host=localhost port=5432 dbname=nazwa user=login password=haslo");
  43. if(PQstatus(conn) == CONNECTION_OK) {
  44. printf("connection made\n");
  45.  
  46. doSQL(conn, "DROP TABLE number");
  47. doSQL(conn, "CREATE TABLE number(value INTEGER PRIMARY KEY,name VARCHAR)");
  48. printf("\n\n ---- czy wpisujemy cos do tabeli? (t/n) ");
  49. while( (odp = getchar()) == 't' || (odp == 'T') ) {
  50. //getchar();
  51. printf(" numer = "); scanf("%d",&value);
  52. printf(" nazwa = "); scanf("%s",name);
  53. getchar();
  54. sprintf(zapytanie, "INSERT INTO number VALUES(%d, \'%s\')",value,name);
  55. //printf("%s\n",zapytanie);
  56. doSQL(conn, zapytanie);
  57. printf("\n\n ---- czy wpisujemy cos do tabeli? (t/n) ");
  58. }
  59.  
  60. doSQL(conn, "SELECT * FROM number");
  61. doSQL(conn, "UPDATE number SET name = 'Zaphod' WHERE value = 1");
  62. doSQL(conn, "DELETE FROM number WHERE value = 2");
  63. doSQL(conn, "SELECT * FROM number");
  64. }
  65. else
  66. printf("connection failed: %s\n", PQerrorMessage(conn));
  67.  
  68. PQfinish(conn);
  69. return EXIT_SUCCESS;
  70. }
Add Comment
Please, Sign In to add comment