MySQL for the Internet of Things

(Steven Felgate) #1

You have also seen how to read data from the file, but not in a way that resulted in inserting the data in
the database. But mechanically, this insert is the same as the write_data() method primitive shown earlier.
Thus, we can reuse this method (write it once, use it multiple places). The following shows the code for the
method:


bool write_data(int val, const char *dateStr) {
String queryStr = String("INSERT INTO plant_moisture.plants VALUES (NULL,");


queryStr += String(val);
queryStr += ",";
if (dateStr != "NULL") queryStr += "'"; // quote string for values
queryStr += dateStr;
if (dateStr != "NULL") queryStr += "'"; // quote string for values
queryStr += ")";
// write the data here
Serial.println(queryStr);
// Create an instance of the cursor passing in the connection
MySQL_Cursor *cur = new MySQL_Cursor(&conn);
cur->execute(queryStr.c_str());
delete cur;
}


Notice here I’ve written the code to detect whether the date string passed is NULL (a character string, not
the null concept or even 0 or \0 terminators). If the string is not NULL, the string is a date and time value, and
we must place quotes around it in the resulting INSERT statement.
That’s it. We have all the methods from the high-level algorithm covered. We need only implement the
required startup code for the RTC, SD card, and MySQL Connector/Arduino. Listing 8-7 shows the complete
code for this sketch.


Listing 8-7. Fault-Tolerant Data Collector


/**
Example Arduino fault tolerant data collector


This project demonstrates how to save data to a
microSD card as a cache should the node fail to
save data to a MySQL database server.
*/
#include <Wire.h>
#include <SD.h>
#include <SPI.h>
#include <Ethernet.h>
#include <MySQL_Connection.h>
#include <MySQL_Cursor.h>
#include "RTClib.h"


// Pin assignment for Arduino Ethernet shield
#define SD_PIN 4
// Pin assignment for Sparkfun microSD shield
//#define SD_PIN 8
// Pin assignment for Adafruit Data Logging shield
//#define SD_PIN 10


ChapTEr 8 ■ DEmonsTraTion of high availabiliTy TEChniquEs

Free download pdf