I am building a water usage sketch that monitors usage via a flowmeter and updates a MYSQL database. The code that I have been using to post to the database suddenly stopped working. Unfortunately it recently stopped working. I isolated just the MYSQL part of the code and inserted it below.
I can still connect to the database remotely from the same IP using my computer and via external website.
It hangs up in trying to connect to the database, the monitor kicks out:
".
WiFi connected.
...trying..."
and freezes.
Any suggestions or advice on trouble shooting code would be greatly appreciated.
board = adafruit_feather_esp32s3_reversetft
framework = arduino
lib_deps =
chuckbell/MySQL Connector Arduino@^1.2.0
code:
#include <WiFi.h>
#include <MySQL_Connection.h>
#include <MySQL_Cursor.h>
// Replace with your network credentials
const char* ssid = "#######";
const char* password = "#######";
// Replace with your MySQL server credentials
IPAddress server_addr(###, ###, ###, ###); // MySQL server IP
char user[] = "#######";
char passwordDB[] = "#######";
char database[] = "#######";
WiFiClient client;
MySQL_Connection conn((Client *)&client);
void insertRow(const char* tableName, const char* columns, const char* values) {
// Connect to MySQL server
if (!conn.connect(server_addr, 3306, user, passwordDB)) {
Serial.println("Failed to connect to MySQL server.");
return;
}
Serial.println("Connected to MySQL server.");
// Select the database
char useDBQuery[128];
snprintf(useDBQuery, sizeof(useDBQuery), "USE %s", database);
MySQL_Cursor* cursor = new MySQL_Cursor(&conn);
if (!cursor->execute(useDBQuery)) {
Serial.println("Failed to select database.");
delete cursor;
return;
}
// Build the INSERT query
char insertQuery[256];
snprintf(insertQuery, sizeof(insertQuery), "INSERT INTO %s (%s) VALUES (%s)", tableName, columns, values);
if (cursor->execute(insertQuery)) {
Serial.println("Row inserted successfully.");
} else {
Serial.println("Failed to insert row.");
}
delete cursor;
}
void setup() {
Serial.begin(115200);
// Connect to WiFi
Serial.println("Connecting to WiFi...");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("\nWiFi connected.");
// Example usage
insertRow("your_table_name", "column1, column2", "'value1', 'value2'");
}
void loop() {
// Empty loop
}