MySQL for the Internet of Things

(Steven Felgate) #1
Chapter 6 ■ Building low-Cost MysQl data nodes

After the delay, you print a statement to the serial monitor to indicate that you are attempting to
connect to the server. Connecting to the server is a single call to the Connector/Arduino library named
connect(). You pass the IP address of the MySQL database server, the port the server is listening on, and the
username and password. If this call passes, the code drops to the next delay() method call.
This delay is needed to slow execution before issuing additional MySQL commands. Like the previous
delay, depending on your hardware and network latency, you may not need this delay. You should
experiment if you have strong feelings against using delays to avoid latency issues. On the other hand,
should the connection fail, the code falls through to the print statement to tell you the connection has failed.


Running a Query


Now it is time to run the query. We first instantiate an instance of the MySQL_Cursor class and pass in the
connection instance. This will dtynamically allocate the class (think code). We then call the execute()
method and pass in the query we want to run. Since there are no results returned (because we’re running an
INSERT), we can close the connection and delete the instance. The following shows all these steps in order.
Place this code in the branch that is executed after a successful connection. The following shows the
previous conditional statement rewritten to include the method call to run the insert query:


if (conn.connect(server_addr, 3306, user, password))
{
delay(500);
/ Write Hello to MySQL table test_arduino.hello /
// Create an instance of the cursor passing in the connection
MySQL_Cursor *cur = new MySQL_Cursor(&conn);
cur->execute(INSERT_SQL);
delete cur;
}
else
Serial.println("Connection failed.");
}


Notice that you simply invoke a method named execute() and pass it the query you defined earlier.
Yes, it is that easy!


Testing the Sketch


You now have all the code needed to complete the sketch except for the loop() method. In this case, you
make it an empty method because you are not doing anything repetitive. Listing 6-5 shows the completed
sketch.


■Tip if you are having problems getting the connector working, see the “troubleshooting Connector/arduino”


section in the MysQl Connector reference Manual^15 and then return to this project.


(^15) https://github.com/ChuckBell/MySQL_Connector_Arduino/blob/master/extras/MySQL_Connector_Arduino_
Reference_Manual.pdf

Free download pdf