feat(multiple_rows): initial commit

This commit is contained in:
dancingCycle 2023-03-15 15:44:43 +01:00
parent 4ebf5eb333
commit 1523aff35d
3 changed files with 112 additions and 0 deletions

65
multiple_rows/main.c Normal file
View File

@ -0,0 +1,65 @@
#include <stdio.h>
#include <stdlib.h>
#include <libpq-fe.h>
void do_exit(PGconn *conn) {
PQfinish(conn);
exit(1);
}
int main(int argc, char **argv) {
/*declaration*/
const char *conninfo;
printf("main() Started...\n");
/*read command line*/
if (argc > 1){
printf("main() argv[1]: %s\n", argv[1]);
conninfo = argv[1];
}else{
printf("call ./main <connection info>\n");
return 1;
}
/*connect to database*/
PGconn *conn = PQconnectdb(conninfo);
if (PQstatus(conn) == CONNECTION_BAD) {
fprintf(stderr, "Connection to database failed: %s\n",
PQerrorMessage(conn));
do_exit(conn);
}else if(PQstatus(conn)==CONNECTION_OK){
printf("main() connected to database\n");
}else{
printf("main() connection status NOT known\n");
}
char *user = PQuser(conn);
char *db_name = PQdb(conn);
char *pswd = PQpass(conn);
printf("User: %s\n", user);
printf("Database name: %s\n", db_name);
printf("Password: %s\n", pswd);
/*retrive server of database using SQL statement*/
/*PGRES_TUPLS_OK is returned for a query that returns data*/
PGresult *res = PQexec(conn, "SELECT * FROM entities");
if (PQresultStatus(res) != PGRES_TUPLES_OK) {
printf("No data retrieved\n");
PQclear(res);
do_exit(conn);
}
/*return the number of rows in the query result*/
int rows = PQntuples(res);
for(int i=0; i<rows; i++){
printf("%s %s \n", PQgetvalue(res,i,0),
PQgetvalue(res,i,1));
}
PQclear(res);
PQfinish(conn);
return 0;
}

24
multiple_rows/makefile Normal file
View File

@ -0,0 +1,24 @@
# Docu
#
#$@ is the name of the file to be made
#$? is the names of the changed dependents
#$< the name of the related file that caused the action
#$* the prefix shared by target and dependent files
#
# Others
RM = /bin/rm -f
#
# Source, Executable, Includes, Library Defines
EXE = main
#
# Compiler, Linker Defines
CC = /usr/bin/gcc
#
all: main.o
$(CC) main.c -I/usr/include/postgresql -L/usr/lib/x86_64-linux-gnu -lpq -std=c99 -Wall -o $(EXE)
#
main.o:
$(CC) -c main.c -I/usr/include/postgresql
# Clean Up Objects, Exectuables, Dumps out of source directory
clean:
$(RM) *.o $(EXE) *~

23
multiple_rows/readme.md Normal file
View File

@ -0,0 +1,23 @@
* build
```
make
```
* run
```
./main 'postgresql://<user>:<secret>@<hostname>:<port>/<db>'
```
* or run
```
./main 'postgresql://<user>:<secret>@<hostname>:<port>/<db>'
```
* or run
```
./main "host=<hostname> port=<port> user=<user> password=<<secret>> dbname=<db>"
```