使用 Arduino UNO R3、Arduino Mega 2560 R3 或 NodeMCU-32s 連結(Connection) MySQL 資料庫(Database)。
範例碼(一):
// ==========================================
#include <WiFi.h>
#include <MySQL_Connection.h>
#include <MySQL_Cursor.h>
// change to your WIFI SSID
const char ssid[] = "SSID";
// change to your WIFI Password
const char password[] = "********";
// change to you server ip, note its form split by "," not "."
IPAddress server_addr(192,168,3,110);
// mysql port default is 3306
int MYSQLPort =3307;
// Your MySQL user login username(default is root),and note to change MYSQL user root can access from local to internet(%)
char user[] = "root";
// Your MYSQL password
char pass[] = "1234";
WiFiClient client;
MySQL_Connection conn((Client *)&client);
// ==========================================
void setup() {
Serial.begin(115200);
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
// try to connect to WIFI
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
// try to connect to mysql server
if (conn.connect(server_addr, 3307, user, pass)) {
delay(1000);
}
else{
Serial.println("Connection failed.");
}
delay(2000);
// insert, change database name and values by string and char[]
// char INSERT_SQL[] = "INSERT INTO DatabaseName.TableName(temp, humd) VALUES('50', '30')";
// or
String INSERT_SQL = "INSERT INTO DatabaseName.TableName(temp, humd) VALUES('" + String(temp) + "', '" + String(humd) + "')";
MySQL_Cursor *cur_mem = new MySQL_Cursor(&conn);
// execute
// for INSERT_SQ
cur_mem->execute(INSERT_SQL.c_str());
// for INSERT_SQL[]
// cur_mem->execute(INSERT_SQL);
delete cur_mem;
Serial.println("Data Saved.");
}
void loop() {
//do nothing
}
Reference:https://youyouyou.pixnet.net/blog/post/119595672
文章標籤
全站熱搜

留言功能已依作者設定調整顯示方式