0

I have one RaspberryPi 3B+ that is hosting a MySQL server. Now I want to write to that database from a remote RaspberryPi Zero that is on the same network. Running my code that attempts to insert a temperature value in my table called home, I get the following error:

mysql.connector.errors.ProgrammingError: Cursor is not connected

This is my code:

import mysql.connector

class Writer:
      
    def __init__(self):
        # --- Connecting to Database ---
        self.con = mysql.connector.connect(
          host= <rpi3 ip>,
          user= <remote user>,
          password= <password>,
          database= <db>
        )

        self.cur = self.con.cursor()

    #Creates the command string for the SQL query       
    def __build_string(self,table,names):
        v = ""
        s = ""
        for i in names:
            v = v + i + ","
            s = s + "%s,"
        v = v[:-1]
        s = s[:-1]
        return "INSERT INTO " + table + " (" + v + ") VALUES (" + s + ")"
    
    def write(self,table,names,values):
        
        command_string = self.__build_string(table,names)

        self.cur.execute(command_string,values)
        self.con.commit()
        return

        
    def terminate_connection(self):
        self.cur.close()
        self.con.close()
        return

def main():
    sql = Writer()
    sql.write('home',[temperature],20)
    sql.terminate_connection()
    
if __name__ == "__main__":
    main()

I have read the this post and tried that answer but with no succes.

This is what I have done so far:

  1. In my rapberryPi 3 that hosts the MySQL server, I created <remote_user> and granted privileges to the user in the following way.
create user '<remote user>'@<rpi3 ip> identified by <password>;
grant all privileges on <db>.home to '<remote user>'@<rpi3 ip>;
  1. There was no [mysqld] section in etc/mysql/my.cnf, so I added the following section to my.cnf
[mysqld]
# Adding to allow conection from remote pi?
bind-address = 0.0.0.0
  1. Install the mysql.connector package on my raspberryPi Zero.
  2. Successfully pinged the raspebberyPi 3 from the raspberryPi Zero.
  3. Changing bind address to 127.0.0.1 resulting in a different error message:

mysql.connector.errors.InterfaceError: 2003: Can't connect to MySQL server on ':3306'

  1. Flushed priveleges in my MySQL server with the following command:
FLUSH PRIVILEGES;
  1. I sucsefully accessed the MySQL server on my RaspberryPi 3B via the comand line on my RaspberryPi Zero using below command
sudo mysql -u <remote user> -h <rpi3 ip> -p

I do not have a firewall installed on any of my Pi's so no ports should be closed.

JabbaThePadd
  • 97
  • 1
  • 7

0 Answers0