-
Notifications
You must be signed in to change notification settings - Fork 0
/
insert.c
51 lines (43 loc) · 1.33 KB
/
insert.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
#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h>
static int callback(void *NotUsed, int argc, char **argv, char **azColName) {
int i;
for(i = 0; i<argc; i++) {
printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
}
printf("\n");
return 0;
}
int insert(int id, char *first_name, char *last_name, int age) {
sqlite3 *db;
char *zErrMsg = 0;
int rc;
/* Open database */
rc = sqlite3_open("data/students.db", &db);
/* Create SQL statement */
const char *sql = "INSERT INTO STUDENTS (ID, FIRST_NAME, LAST_NAME, AGE) VALUES (?, ?, ?, ?);";
const char *pzTail;
sqlite3_stmt *stmt;
sqlite3_prepare_v2(db, sql, 512, &stmt, &pzTail);
sqlite3_bind_int(stmt, 1, id);
sqlite3_bind_text(stmt, 2, first_name, -1, SQLITE_STATIC);
sqlite3_bind_text(stmt, 3, last_name, -1, SQLITE_STATIC);
sqlite3_bind_int(stmt, 4, age);
while (sqlite3_step(stmt) != SQLITE_DONE) {}
sqlite3_finalize(stmt);
/* Execute SQL statement */
rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg);
if(rc != SQLITE_OK) {
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
} else {
fprintf(stdout, "Records created successfully\n");
}
sqlite3_close(db);
return 0;
}
int main(int argc, char *argv[]) {
insert(1, "Annie", "Sohal", 19);
return 0;
}