SQL Database insert

Hello I would like to insert a RFID in a Database. With my code it's possible to connect with the database, read RFID Cards an insert manual values.

How can I insert a variable? I would like to insert the Value of the variable "dump_byte_array".

Here is my code:

/*
   Michel Kempf
*/

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


#define RST_PIN         9         
#define SS_PIN          8
const byte RFID_CS_pin = 8;


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

IPAddress server_addr(10,44,24,10);
char user[] = "rfid";            
char password[] = "jekfuekjJJFKJEfAF";      

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

      

MFRC522 mfrc522(SS_PIN, RST_PIN);   // Instanz für MFRC522 erzeugen

// Sample query
char INSERT_SQL[] = "INSERT INTO DB2017_RFID.TAG_Data (ID_TAG) VALUES ('dump_byte_array')";


#define NR_KNOWN_KEYS   8
byte knownKeys[NR_KNOWN_KEYS][MFRC522::MF_KEY_SIZE] =  {
   {0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, // FF FF FF FF FF FF = factory default
   {0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5}, // A0 A1 A2 A3 A4 A5
   {0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5}, // B0 B1 B2 B3 B4 B5
   {0x4d, 0x3a, 0x99, 0xc3, 0x51, 0xdd}, // 4D 3A 99 C3 51 DD
   {0x1a, 0x98, 0x2c, 0x7e, 0x45, 0x9a}, // 1A 98 2C 7E 45 9A
   {0xd3, 0xf7, 0xd3, 0xf7, 0xd3, 0xf7}, // D3 F7 D3 F7 D3 F7
   {0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff}, // AA BB CC DD EE FF
   {0x00, 0x00, 0x00, 0x00, 0x00, 0x00}  // 00 00 00 00 00 00
};

/*
* Inizialisieren
*/
void setup()
 
{
   

   Serial.begin(9600);         // Initialisiere serielle Verbindung mit dem Computer
   while (!Serial);            // Mache nichts wenn der serielle Port nicht frei ist
   SPI.begin();                // Initialisiere SPI bus
   pinMode(RFID_CS_pin, OUTPUT);
   digitalWrite(RFID_CS_pin, HIGH);  //Deselect the RFID reader
   Ethernet.begin(mac_addr);
   
   mfrc522.PCD_Init();     // Initialisiere MFRC522 card
   SPI.usingInterrupt(10);
   //Serial.println(F("Try the most used default keys to print block 0 of a MIFARE PICC."));
   SPI.usingInterrupt(10);
   Serial.println("RFID Projekt");
   Serial.println("=====================");

   Serial.println("Verbinden...");
 if (conn.connect(server_addr, 3306, user, password)) {
   Serial.println("Verbindung erstellt...");
   delay(1000);
 
 }
 /*else
   Serial.println("Verbindung fehlgeschlagen.");
 conn.close();*/
}

/*
* Hex Werte für die Serielle Übertragung
*/
void dump_byte_array(byte *buffer, byte bufferSize) {
   for (byte i = 0; i < bufferSize; i++) {
       Serial.print(buffer[i] < 0x10 ? " 0" : " ");
       Serial.print(buffer[i], HEX);
   }
}

//Keytest
boolean try_key(MFRC522::MIFARE_Key *key)
{
   boolean result = false;
   byte buffer[18];
   byte block = 0;
   MFRC522::StatusCode status;
   
   if ( ! mfrc522.PICC_IsNewCardPresent())
       return false;
   if ( ! mfrc522.PICC_ReadCardSerial())
       return false;
   // Serial.println(F("Authenticating using key A..."));
   status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, key, &(mfrc522.uid));
   if (status != MFRC522::STATUS_OK) {
       //Serial.print(F("PCD_Authenticate() failed: "));
       //Serial.println(mfrc522.GetStatusCodeName(status));
       return false;
   }

   // Lesen
   byte byteCount = sizeof(buffer);
   status = mfrc522.MIFARE_Read(block, buffer, &byteCount);
   if (status != MFRC522::STATUS_OK) {
       //Serial.print(F("MIFARE_Read() failed: "));
       //Serial.println(mfrc522.GetStatusCodeName(status));
   }

   mfrc522.PICC_HaltA();       // Halt PICC
   mfrc522.PCD_StopCrypto1();  // Stopt die RC522 Entschlüsselnung
   return result;
}

/*
* Main loop
*/
void loop() {  
 
   // Neue Karte
   if ( ! mfrc522.PICC_IsNewCardPresent())
   
       return;
       

   // Bekannte Karte
   if ( ! mfrc522.PICC_ReadCardSerial())
       return;

   // Anzeige
   Serial.print(F("BAG")); //Überschrift
   Serial.println();
   Serial.print(F("ID:")); //ID Überschrift
   dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size); //ID Ausgabe
   Serial.println();
   Serial.println("---------------------");
   delay(1000); // Pause beim Auslesen

   Serial.println("Schreiben in Datenbank.");
       
       
         
   
   
   // Überprüfung von unbekannten Schlüsseln
   MFRC522::MIFARE_Key key;
   for (byte k = 0; k < NR_KNOWN_KEYS; k++) {
       // Kopieren des Chips ind die MIFARE_Key Struktur
       for (byte i = 0; i < MFRC522::MF_KEY_SIZE; i++) {
           key.keyByte[i] = knownKeys[k][i];
       }
       // Testen des Chips
       if (try_key(&key)) {
           // Chip gefunden
           break;
       }
   }

   MySQL_Cursor *cur_mem = new MySQL_Cursor(&conn);
       
         cur_mem->execute(INSERT_SQL);
         delete cur_mem;
}

Hello I would like to insert a RFID in a Database.

Does that make sense? How can you put hardware in a database?

How can I insert a variable? I would like to insert the Value of the variable "dump_byte_array".

dump_byte_array is NOT a variable. That stupidly named function does print the value of a variable (an array, actually).

You COULD construct a more meaningful representation of the byte array, and then copy the contents of whatever variable holds that more meaningful representation into the variable that contains the INSERT statement.

I KNOW for a fact that your code does not look like that. Read the stickies at the top of the forum and fix your post.

Can you give me an example how do that should look like?

Hey there

I would like to insert the values of the function dump_byte_array in a Database. The connection is working.

Here is my Code:

/*
   Michel Kempf
*/

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


#define RST_PIN         9         
#define SS_PIN          8
const byte RFID_CS_pin = 8;


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

IPAddress server_addr(10,44,24,10);
char user[] = "rfid";           
char password[] = "3jQAesPbi5R5M7ipTsUB";     

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

     

MFRC522 mfrc522(SS_PIN, RST_PIN);   // Instanz für MFRC522 erzeugen

// Sample query
char INSERT_SQL[] = "INSERT INTO DB2017_RFID.TAG_Data (ID_TAG) VALUES ('test')";



#define NR_KNOWN_KEYS   8
byte knownKeys[NR_KNOWN_KEYS][MFRC522::MF_KEY_SIZE] =  {
   {0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, // FF FF FF FF FF FF = factory default
   {0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5}, // A0 A1 A2 A3 A4 A5
   {0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5}, // B0 B1 B2 B3 B4 B5
   {0x4d, 0x3a, 0x99, 0xc3, 0x51, 0xdd}, // 4D 3A 99 C3 51 DD
   {0x1a, 0x98, 0x2c, 0x7e, 0x45, 0x9a}, // 1A 98 2C 7E 45 9A
   {0xd3, 0xf7, 0xd3, 0xf7, 0xd3, 0xf7}, // D3 F7 D3 F7 D3 F7
   {0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff}, // AA BB CC DD EE FF
   {0x00, 0x00, 0x00, 0x00, 0x00, 0x00}  // 00 00 00 00 00 00
};

/*
* Inizialisieren
*/
void setup()
 
{
   

   Serial.begin(9600);         // Initialisiere serielle Verbindung mit dem Computer
   while (!Serial);            // Mache nichts wenn der serielle Port nicht frei ist
   SPI.begin();                // Initialisiere SPI bus
   pinMode(RFID_CS_pin, OUTPUT);
   digitalWrite(RFID_CS_pin, HIGH);  //Deselect the RFID reader
   Ethernet.begin(mac_addr);
   
   mfrc522.PCD_Init();     // Initialisiere MFRC522 card
   SPI.usingInterrupt(10);
   //Serial.println(F("Try the most used default keys to print block 0 of a MIFARE PICC."));
   SPI.usingInterrupt(10);
   Serial.println("RFID Projekt");
   Serial.println("=====================");

   Serial.println("Verbinden...");
 if (conn.connect(server_addr, 3306, user, password)) {
   Serial.println("Verbindung erstellt...");
   delay(1000);
 
 }
 /*else
   Serial.println("Verbindung fehlgeschlagen.");
 conn.close();*/
}

/*
* Hex Werte für die Serielle Übertragung
*/
void dump_byte_array(byte *buffer, byte bufferSize) {
   for (byte i = 0; i < bufferSize; i++) {
       Serial.print(buffer[i] < 0x10 ? " 0" : " ");
       Serial.print(buffer[i], HEX);
   }
}

//Keytest
boolean try_key(MFRC522::MIFARE_Key *key)
{
   boolean result = false;
   byte buffer[18];
   byte block = 0;
   MFRC522::StatusCode status;
   
   if ( ! mfrc522.PICC_IsNewCardPresent())
       return false;
   if ( ! mfrc522.PICC_ReadCardSerial())
       return false;
   // Serial.println(F("Authenticating using key A..."));
   status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, key, &(mfrc522.uid));
   if (status != MFRC522::STATUS_OK) {
       //Serial.print(F("PCD_Authenticate() failed: "));
       //Serial.println(mfrc522.GetStatusCodeName(status));
       return false;
   }

   // Lesen
   byte byteCount = sizeof(buffer);
   status = mfrc522.MIFARE_Read(block, buffer, &byteCount);
   if (status != MFRC522::STATUS_OK) {
       //Serial.print(F("MIFARE_Read() failed: "));
       //Serial.println(mfrc522.GetStatusCodeName(status));
   }

   mfrc522.PICC_HaltA();       // Halt PICC
   mfrc522.PCD_StopCrypto1();  // Stopt die RC522 Entschlüsselnung
   return result;
}

/*
* Main loop
*/
void loop() { 
 
   // Neue Karte
   if ( ! mfrc522.PICC_IsNewCardPresent())
   
       return;
       

   // Bekannte Karte
   if ( ! mfrc522.PICC_ReadCardSerial())
       return;

   // Anzeige
   Serial.print(F("BAG")); //Überschrift
   Serial.println();
   Serial.print(F("ID:")); //ID Überschrift
   dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size); //ID Ausgabe
   Serial.println();
   Serial.println("---------------------");
   delay(1000); // Pause beim Auslesen

   Serial.println("Schreiben in Datenbank.");
       
       
         
   
   
   // Überprüfung von unbekannten Schlüsseln
   MFRC522::MIFARE_Key key;
   for (byte k = 0; k < NR_KNOWN_KEYS; k++) {
       // Kopieren des Chips ind die MIFARE_Key Struktur
       for (byte i = 0; i < MFRC522::MF_KEY_SIZE; i++) {
           key.keyByte[i] = knownKeys[k][i];
       }
       // Testen des Chips
       if (try_key(&key)) {
           // Chip gefunden
           break;
       }
   }

  
   MySQL_Cursor *cur_mem = new MySQL_Cursor(&conn);
       
         cur_mem->execute(INSERT_SQL);
         delete cur_mem;
}

What is the problem you're facing? What did you try? Have you tried the SQL query on the DB server directly? (E.g. using the MySQL prompt or a web tool like phpMyAdmin.)

Generally, it's not recommended to have your database server open to the network. It's common practice to restrict database connections to the local machine only.
You can then use a simple PHP script with a few lines of PDO that takes data from an HTTP request, escapes it and inserts it into the DB. (And a second script to retrieve the data of you have to.)
This improves security, and makes the Arduino code a lot easier, because you just have to make an HTTP request, not an actual database connection.

Pieter

I use a phpMyAdmin Database. In my opinion it's a lot easier with a connection in the arduino code. I can insert test as a text but i would like to insert the values of the function dump_byte_array. The problem is I don't know how.

PhpMyAdmin is not a database, it's just a front-end tool that allows you to interact with the underlying database and database server (probably MySQL).

What's the easiest method may be up for debate, but it's definitely safer to refuse external DB connections. And if you're using an SQL server with PhpMyAdmin, you probably already have Apache and PHP installed and running anyway.

What data type is the column you're trying to insert it in?
SQL queries are text based, so you have to convert your byte array to a (hexadecimal) string representation of the numbers. Have you tried adding the "0x" prefix?

Pieter

I would like to insert a String in the column. I don't know how to insert a value of variable in a function.

With this code it's possible to insert the word test:

har INSERT_SQL[] = "INSERT INTO DB2017_RFID.TAG_Data (ID_TAG) VALUES ('test')";

But I would like to insert the value of this function:

void dump_byte_array(byte *buffer, byte bufferSize) {
   for (byte i = 0; i < bufferSize; i++) {
       Serial.print(buffer[i] < 0x10 ? " 0" : " ");
       Serial.print(buffer[i], HEX);
   }
}

I can put out the values in the serial monitor with this code:

dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);

You could use a String object instead of a null terminated char array, this let's you concatenate Strings very easily. You can also convert it to HEX directly.

You can use this to test your program, but it's not recommended to use Strings (note the capital S) in the final program, because it could cause memory fragmentation in the long run (it's dynamically allocated). It's better to use strings or char arrays instead of Strings. You could use a fixed char buffer, and use strcpy and strcat to generate the final SQL query.

Pieter

How can i program a string object? Can you make a example with my code?

String query = "INSERT INTO DB2017_RFID.TAG_Data (ID_TAG) VALUES ('0x";
for (byte i = 0; i < bufferSize; i++) {
    query += buffer[i] < 0x10 ? " 0" : " ";
    query += String(buffer[i], HEX);
}
query += "')";

This code isn't working. Have I done a mistake?

It should go inside the dump_byte_array function. Not sure what's wrong with that line, though... Maybe you have to escape the ' character?

Pieter

I know that phpMyAdmin is a dbms.

Then you don't know jack.

This is my new Code:

/*
   Michel Kempf
*/

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



#define RST_PIN         9         
#define SS_PIN          8
const byte RFID_CS_pin = 8;


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

IPAddress server_addr(10,44,24,10);
char user[] = "rfid";           
char password[] = "3jQAesPbi5R5M7ipTsUB";     

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

     

MFRC522 mfrc522(SS_PIN, RST_PIN);   // Instanz für MFRC522 erzeugen

// Sample query
//char insert_sqlRT_SQL[] = "insert_sqlRT INTO DB2017_RFID.TAG_Data (ID_TAG) VALUES ('test')";

String insert_sql;




#define NR_KNOWN_KEYS   8
byte knownKeys[NR_KNOWN_KEYS][MFRC522::MF_KEY_SIZE] =  {
   {0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, // FF FF FF FF FF FF = factory default
   {0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5}, // A0 A1 A2 A3 A4 A5
   {0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5}, // B0 B1 B2 B3 B4 B5
   {0x4d, 0x3a, 0x99, 0xc3, 0x51, 0xdd}, // 4D 3A 99 C3 51 DD
   {0x1a, 0x98, 0x2c, 0x7e, 0x45, 0x9a}, // 1A 98 2C 7E 45 9A
   {0xd3, 0xf7, 0xd3, 0xf7, 0xd3, 0xf7}, // D3 F7 D3 F7 D3 F7
   {0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff}, // AA BB CC DD EE FF
   {0x00, 0x00, 0x00, 0x00, 0x00, 0x00}  // 00 00 00 00 00 00
};

/*
* Inizialisieren
*/
void setup()
 
{
   

   Serial.begin(9600);         // Initialisiere serielle Verbindung mit dem Computer
   while (!Serial);            // Mache nichts wenn der serielle Port nicht frei ist
   SPI.begin();                // Initialisiere SPI bus
   pinMode(RFID_CS_pin, OUTPUT);
   digitalWrite(RFID_CS_pin, HIGH);  //Deselect the RFID reader
   Ethernet.begin(mac_addr);
   
   mfrc522.PCD_Init();     // Initialisiere MFRC522 card
   SPI.usingInterrupt(10);
   //Serial.println(F("Try the most used default keys to print block 0 of a MIFARE PICC."));
   SPI.usingInterrupt(10);
   Serial.println("RFID Projekt");
   Serial.println("=====================");

   Serial.println("Verbinden...");
 if (conn.connect(server_addr, 3306, user, password)) {
   Serial.println("Verbindung erstellt...");
   delay(1000);
 
 }
 else
   Serial.println("Verbindung fehlgeschlagen.");
 /*conn.close();*/
}



/*
* Hex Werte für die Serielle Übertragung
*/
void dump_byte_array(byte *buffer, byte bufferSize) {
   String insert_sql = "insert_sqlRT INTO DB2017_RFID.TAG_Data (ID_TAG) VALUES ('0x";
    for (byte i = 0; i < bufferSize; i++) {
    insert_sql += buffer[i] < 0x10 ? " 0" : " ";
    insert_sql += String(buffer[i], HEX);
}
insert_sql += "')";
}

//Keytest
boolean try_key(MFRC522::MIFARE_Key *key)
{
   boolean result = false;
   byte buffer[18];
   byte block = 0;
   MFRC522::StatusCode status;
   
   if ( ! mfrc522.PICC_IsNewCardPresent())
       return false;
   if ( ! mfrc522.PICC_ReadCardSerial())
       return false;
   // Serial.println(F("Authenticating using key A..."));
   status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, key, &(mfrc522.uid));
   if (status != MFRC522::STATUS_OK) {
       //Serial.print(F("PCD_Authenticate() failed: "));
       //Serial.println(mfrc522.GetStatusCodeName(status));
       return false;
   }

   // Lesen
   byte byteCount = sizeof(buffer);
   status = mfrc522.MIFARE_Read(block, buffer, &byteCount);
   if (status != MFRC522::STATUS_OK) {
       //Serial.print(F("MIFARE_Read() failed: "));
       //Serial.println(mfrc522.GetStatusCodeName(status));
   }

   mfrc522.PICC_HaltA();       // Halt PICC
   mfrc522.PCD_StopCrypto1();  // Stopt die RC522 Entschlüsselnung
   return result;
}

/*
* Main loop
*/
void loop() { 
 
   // Neue Karte
   if ( ! mfrc522.PICC_IsNewCardPresent())
   
       return;
       

   // Bekannte Karte
   if ( ! mfrc522.PICC_ReadCardSerial())
       return;

   // Anzeige
   Serial.print(F("BAG")); //Überschrift
   Serial.println();
   Serial.print(F("ID:")); //ID Überschrift
   dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size); //ID Ausgabe
   Serial.println();
   Serial.println("---------------------");
   delay(1000); // Pause beim Auslesen

   Serial.println("Schreiben in Datenbank.");
       
       
         
   
   
   // Überprüfung von unbekannten Schlüsseln
   MFRC522::MIFARE_Key key;
   for (byte k = 0; k < NR_KNOWN_KEYS; k++) {
       // Kopieren des Chips ind die MIFARE_Key Struktur
       for (byte i = 0; i < MFRC522::MF_KEY_SIZE; i++) {
           key.keyByte[i] = knownKeys[k][i];
       }
       // Testen des Chips
       if (try_key(&key)) {
           // Chip gefunden
           break;
       }
   }


   MySQL_Cursor *cur_mem = new MySQL_Cursor(&conn);
       
   cur_mem->execute(insert_sql);
   delete cur_mem;
}

There is the line which returns an error:

   cur_mem->execute(insert_sql);

There is the line which returns an error:

We need another round of post/replies because you didn't post the error AS TEXT.

Try insert_sql.c_str().

Pieter

This is the error as text:

Arduino: 1.8.2 (Windows 10), Board: "Arduino/Genuino Uno"

C:\Users\mkempf.BLJ\Pictures\sketch_jun21a\sketch_jun21a.ino: In function 'void loop()':

sketch_jun21a:177: error: no matching function for call to 'MySQL_Cursor::execute(String&)'

    cur_mem->execute(insert_sql);

                               ^

C:\Users\mkempf.BLJ\Pictures\sketch_jun21a\sketch_jun21a.ino:177:31: note: candidate is:

In file included from C:\Users\mkempf.BLJ\Pictures\sketch_jun21a\sketch_jun21a.ino:9:0:

C:\Users\mkempf.BLJ\Documents\Arduino\libraries\MySQL_Connector_Arduino-master\src/MySQL_Cursor.h:63:13: note: boolean MySQL_Cursor::execute(const char*, boolean)

     boolean execute(const char *query, boolean progmem=false);

             ^

C:\Users\mkempf.BLJ\Documents\Arduino\libraries\MySQL_Connector_Arduino-master\src/MySQL_Cursor.h:63:13: note:   no known conversion for argument 1 from 'String' to 'const char*'

Multiple libraries were found for "MFRC522.h"
 Used: C:\Users\mkempf.BLJ\Documents\Arduino\libraries\MFRC522
 Not used: C:\Users\mkempf.BLJ\Documents\Arduino\libraries\rfid-master
exit status 1
no matching function for call to 'MySQL_Cursor::execute(String&)'

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

PieterP:
Try insert_sql.c_str().

Pieter

In which part of the code should I place

insert_sql.c_str().

?