如何从Arduino连接到数据库?

时间:2019-05-31 08:13:11

标签: mysql arduino ethernet

我想将数据从数据库传输到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.");
}

1 个答案:

答案 0 :(得分:2)

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

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.");
}