首页 > 解决方案 > 如何从 Arduino 连接到数据库?

问题描述

我想将数据从数据库传输到 Arduino。为此,我在 Arduino 中使用 MYSQL_Connector 库。但我收到这样的错误:“连接失败”。我无法连接到数据库。另外,我正在使用 XAMPP 服务器。

我检查了 MYSQL 服务器的 IP 地址、端口和用户名密码。

#include <SPI.h>
#include <Ethernet.h>
#include <MySQL_Connection.h>
#include <MySQL_Cursor.h>

byte mac_addr[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

IPAddress server_addr(x,x,x,x);  // the IP address to that of the system on which my MySQL server is set up
char user[] = "user";              // MySQL user login username
char password[] = "1234";        // MySQL user login password


// Sample query
char query[] = "SELECT id FROM world.city";

EthernetClient client;
MySQL_Connection conn((Client *)&client);

void setup() {
  Serial.begin(9600);
  while (!Serial); // wait for serial port to connect
  Ethernet.begin(mac_addr);
  Serial.println("Connecting...");
  if (conn.connect(server_addr, 8080, user, password)) {
    delay(1000);
  }
  else
    Serial.println("Connection failed.");
}

标签: mysqlarduinoethernet

解决方案


我已经解决了这个问题。问题是您还需要授予用户访问您想要访问的任何数据库的权限。首先,您需要创建用户。您可以使用下面的链接。

https://st2.ning.com/topology/rest/1.0/file/get/2053761171?profile=original

#include <Ethernet.h>
#include <MySQL_Connection.h>
#include <MySQL_Cursor.h>

byte mac_addr[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

IPAddress server_addr(x,x,x,x);  //the IP address to that of the system on which my MySQL server is set up
char user[] = "bob";              // MySQL user login username
char password[] = "secret";        // MySQL user login password


// Sample query
char query[] = "SELECT id FROM world.city";

EthernetClient client;
MySQL_Connection conn((Client *)&client);

void setup() {
  Serial.begin(9600);
  while (!Serial); // wait for serial port to connect
  Ethernet.begin(mac_addr);

  //while(!conn.connect(server_addr, 3306, user, password));

  Serial.println("Connecting...");
  if (conn.connect(server_addr, 3306, user, password)) {
    delay(1000);
  }
  else
    Serial.println("Connection failed.");
}

推荐阅读