esp8266连接本地数据库------>arduino ide编译代码(3)

这里首先到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连接本地数据库的全部内容了

  • 7
    点赞
  • 54
    收藏
    觉得还不错? 一键收藏
  • 17
    评论
评论 17
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值