Skip to content

Commit 2a87f4e

Browse files
committed
Add Small Db example
1 parent 74889da commit 2a87f4e

File tree

1 file changed

+96
-0
lines changed

1 file changed

+96
-0
lines changed
Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
/*
2+
This example opens Sqlite3 databases from SD Card and
3+
retrieves data from them.
4+
Before running please copy following files to SD Card:
5+
data/babyname.db
6+
7+
Also increase stack size in cores/esp8266/cont.h
8+
to atleast 6144 (from 4096).
9+
10+
Please see https://github.com/siara-cc/esp_arduino_sqlite3_lib/
11+
for more information.
12+
*/
13+
14+
#include <stdio.h>
15+
#include <stdlib.h>
16+
#include <sqlite3.h>
17+
#include <vfs.h>
18+
#include <SPI.h>
19+
extern "C" {
20+
#include "user_interface.h"
21+
}
22+
#include <ESP8266WiFi.h>
23+
24+
void WiFiOff() {
25+
wifi_station_disconnect();
26+
wifi_set_opmode(NULL_MODE);
27+
wifi_set_sleep_type(MODEM_SLEEP_T);
28+
wifi_fpm_open();
29+
wifi_fpm_do_sleep(0xFFFFFFF);
30+
}
31+
32+
int openDb(const char *filename, sqlite3 **db) {
33+
int rc = sqlite3_open(filename, db);
34+
if (rc) {
35+
Serial.printf("Can't open database: %s\n", sqlite3_errmsg(*db));
36+
return rc;
37+
} else {
38+
Serial.printf("Opened database successfully\n");
39+
}
40+
return rc;
41+
}
42+
43+
void setup ( void ) {
44+
45+
sqlite3 *db1;
46+
int rc;
47+
sqlite3_stmt *res;
48+
int rec_count = 0;
49+
const char *tail;
50+
51+
Serial.begin(74880);
52+
53+
system_update_cpu_freq(SYS_CPU_160MHZ);
54+
WiFiOff();
55+
56+
SPI.begin();
57+
vfs_mount("/SD0", SS);
58+
59+
sqlite3_initialize();
60+
61+
// Open database 1
62+
if (openDb("/SD0/babyname.db", &db1))
63+
return;
64+
65+
String sql = "Select year, state, name, total_babies, primary_sex, primary_sex_ratio, \
66+
per_100k_in_state from gendered_names \
67+
where name between 'Bob' and 'Bobby'";
68+
rc = sqlite3_prepare_v2(db1, sql.c_str(), 1000, &res, &tail);
69+
if (rc != SQLITE_OK) {
70+
String resp = "Failed to fetch data: ";
71+
resp += sqlite3_errmsg(db1);
72+
resp += "<br><br><a href='/'>back</a>";
73+
Serial.println(resp.c_str());
74+
return;
75+
}
76+
77+
while (sqlite3_step(res) == SQLITE_ROW) {
78+
Serial.printf("Year: %d\n", sqlite3_column_int(res, 0));
79+
Serial.printf("State: %s\n", (const char *) sqlite3_column_text(res, 1));
80+
Serial.printf("Name: %s\n", (const char *) sqlite3_column_text(res, 2));
81+
Serial.printf("Total babies: %d\n", sqlite3_column_int(res, 3));
82+
Serial.printf("Primary sex: %s\n", (const char *) sqlite3_column_text(res, 4));
83+
Serial.printf("Ratio: %lf\n", sqlite3_column_double(res, 5));
84+
Serial.printf("Per 100k in state: %lf\n\n", sqlite3_column_double(res, 6));
85+
rec_count++;
86+
}
87+
Serial.printf("No. of records: %d", rec_count);
88+
89+
sqlite3_finalize(res);
90+
91+
sqlite3_close(db1);
92+
93+
}
94+
95+
void loop () {
96+
}

0 commit comments

Comments
 (0)