1 // This is a test program for sqlite3.
2 // We take it from rcore-os/arceos, thanks to @rcore-os community.
3 #include <sqlite3.h>
4 #include <stddef.h>
5 #include <stdio.h>
6 #include <string.h>
7
callback(void * NotUsed,int argc,char ** argv,char ** azColName)8 int callback(void *NotUsed, int argc, char **argv, char **azColName)
9 {
10 NotUsed = NULL;
11
12 for (int i = 0; i < argc; ++i) {
13 printf("%s = %s\n", azColName[i], (argv[i] ? argv[i] : "NULL"));
14 }
15
16 printf("\n");
17
18 return 0;
19 }
20
exec(sqlite3 * db,char * sql)21 void exec(sqlite3 *db, char *sql)
22 {
23 printf("sqlite exec:\n %s\n", sql);
24 char *errmsg = NULL;
25 int rc = sqlite3_exec(db, sql, NULL, NULL, &errmsg);
26 if (rc != SQLITE_OK) {
27 printf("sqlite exec error: %s\n", errmsg);
28 }
29 }
30
query(sqlite3 * db,char * sql)31 void query(sqlite3 *db, char *sql)
32 {
33 printf("sqlite query:\n %s\n", sql);
34 char *errmsg = NULL;
35 int rc = sqlite3_exec(db, sql, callback, NULL, &errmsg);
36
37 if (rc != SQLITE_OK) {
38 printf("%s\n", errmsg);
39 }
40 }
41
query_test(sqlite3 * db,const char * args)42 void query_test(sqlite3 *db, const char *args)
43 {
44 puts("======== init user table ========");
45 exec(db, "create table user("
46 "id INTEGER PRIMARY KEY AUTOINCREMENT,"
47 "username TEXT,"
48 "password TEXT"
49 ")");
50
51 puts("======== insert user 1, 2, 3 into user table ========");
52
53 char cmd[256] = {0};
54 sprintf(cmd,
55 "insert into user (username, password) VALUES ('%s_1', 'password1'), ('%s_2', "
56 "'password2'), ('%s_3', 'password3')",
57 args, args, args);
58 exec(db, cmd);
59
60 puts("======== select all ========");
61 query(db, "select * from user");
62
63 puts("======== select id = 2 ========");
64 query(db, "select * from user where id = 2");
65 }
66
memory()67 void memory()
68 {
69 sqlite3 *db;
70 printf("sqlite open memory\n");
71 int ret = sqlite3_open(":memory:", &db);
72 printf("sqlite open memory status %d \n", ret);
73
74 query_test(db, "memory");
75 }
76
file()77 void file()
78 {
79 sqlite3 *db;
80 int ret = sqlite3_open("file.sqlite", &db);
81 printf("sqlite open /file.sqlite status %d \n", ret);
82
83 if (ret != 0) {
84 printf("sqlite open error");
85 return;
86 }
87
88 query_test(db, "file");
89 sqlite3_close(db);
90 }
91
main()92 int main()
93 {
94 printf("sqlite version: %s\n", sqlite3_libversion());
95
96 memory();
97 file();
98 return 0;
99 }
100