-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2 - create table.c
57 lines (43 loc) · 1.34 KB
/
2 - create table.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
54
55
#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");
// Delete table if exists.
PGresult *res = PQexec(conn, "DROP TABLE IF EXISTS example");
if (PQresultStatus(res) != PGRES_COMMAND_OK) {
fprintf(stderr, "Drop error, %s\n", PQerrorMessage(conn));
PQclear(res);
PQfinish(conn);
exit(0);
}
PQclear(res);
printf("Drop table OK!\n");
// Create new table.
res = PQexec(conn,
" CREATE TABLE example ( "
" id INT, "
" name VARCHAR(100) "
" ); ");
if (PQresultStatus(res) != PGRES_COMMAND_OK) {
fprintf(stderr, "Create error, %s\n", PQerrorMessage(conn));
PQclear(res);
PQfinish(conn);
exit(0);
}
PQclear(res);
printf("Create table OK!\n");
// Close connection.
PQfinish(conn);
printf("Disconnected!\n");
return 0;
}