这里首先到arduino ide的工具那里下载一个库,直接搜索MYSQL即可
,如图下载第一个。
以下我要分享的代码也是通过修改它的历程来体现的。
其中这一句便是对应数据库中的名字以及表的名字:test是数据库的名字,test1是表的名字
char INSERT_SQL[] = "INSERT INTO test.test1(Name,ID,Now_time) VALUES ('%s','%d',now())";
#include <ESP8266WiFi.h> // esp8266库
#include <MySQL_Connection.h> // Arduino连接Mysql的库
#include <MySQL_Cursor.h>
IPAddress server_addr(192,168,xx,xx); // 安装Mysql的电脑的IP地址
char user[] = "root"; // Mysql的用户名
char password[] = "xxxxx"; // 登陆Mysql的密码
// Mysql中添加一条数据的命令
// arduino_test,test1:刚才创建的数据和表
char INSERT_SQL[] = "INSERT INTO test.test1(Name,ID,Now_time) VALUES ('%s','%d',now())";
char ssid[] = "xxxx"; // WiFi名
char pass[] = "xxxxxxx"; // WiFi密码
WiFiClient client; // 声明一个Mysql客户端,在连接Mysql中使用
MySQL_Connection conn(&client);
MySQL_Cursor* cursor; //
int isConnection=0;
char num[]="张三123";
int id=0;
// 读取数据并写入到数据库
void readAndRecordData(){
char buff[128];// 定义存储数据的数组
id+=2;
sprintf(buff,INSERT_SQL,num,id); //
MySQL_Cursor *cur_mem = new MySQL_Cursor(&conn); // 创建一个Mysql实例
cur_mem->execute(buff);
Serial.println("读取数据,并写入数据库");
delete cur_mem; // 删除mysql实例为下次采集作准备
}
void setup()
{
Serial.begin(9600);
while (!Serial); // 等待端口的释放
Serial.printf("\nConnecting to %s", ssid);
WiFi.begin(ssid, pass); // 连接WiFi
while (WiFi.status() != WL_CONNECTED) { // 如果WiFi没有连接,一直循环打印点
delay(500);
Serial.print(".");
}
Serial.println("\nConnected to network");
Serial.print("My IP address is: ");
Serial.println(WiFi.localIP()); // 打印开发板的IP地址
Serial.print("Connecting to SQL... ");
if (conn.connect(server_addr, 3306, user, password)) // 连接数据库
{
isConnection=1;
Serial.println("成功连接数据库---OK.");
}else{
isConnection=0;
Serial.println("连接数据库失败---FAILED.");
}
cursor = new MySQL_Cursor(&conn); // 创建一个数据库游标实例
}
void loop()
{
if(isConnection==1)
{
readAndRecordData();
delay(5000);
}
}
最终结果展示
好了,这便是esp8266连接本地数据库的全部内容了