-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path3 - insert item.c
55 lines (42 loc) · 1.28 KB
/
3 - insert item.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <stdio.h>
#include <stdlib.h>
#include <libpq-fe.h>
#include "settings.h"
int main (int argc, char *argv[])
{
// Connect to the database.
PGconn *conn = PQconnectdb("host=" HOSTNAME " dbname=" DATABASE " user=" USERNAME " password=" PASSWORD);
if (PQstatus(conn) == CONNECTION_BAD) {
fprintf(stderr, "Connection to database failed: %s\n", PQerrorMessage(conn));
PQfinish(conn);
exit(0);
}
printf("Connected!\n");
// Insert new item.
char *stm =
" INSERT INTO example ( "
" id, "
" name "
" ) VALUES ( "
" $1, $2 "
" ); ";
int total_items = 2;
char *items []= {
"1",
"Test item"
};
PGresult *res = PQexecParams(
conn, stm, total_items, NULL, (const char * const*) items, NULL, NULL, 0);
if (PQresultStatus(res) != PGRES_COMMAND_OK) {
fprintf(stderr, "Insert error, %s\n", PQerrorMessage(conn));
PQclear(res);
PQfinish(conn);
exit(0);
}
PQclear(res);
printf("Item successfully inserted into the database.\n");
// Close connection.
PQfinish(conn);
printf("Disconnected!\n");
return 0;
}