I have a class with two variables set to some default value. I have defined a function where I declare these variables as global inside my function. I get this error which says the variable is not defined. One variable is counter, which will increment on each function call and other variable has to append message on each call. After appending multiple messages and counter value reaches some threshold I want to insert all these messages into MySQL database. But the variable is not appending the values. It shows the variable is undefined.
class Message():
insertStatement= ''
insertCounter = 0
def Save(self, msg)
global insertCounter
global insertStatement
if msg.topic.startswith("topic1/"):
insertStatement += "INSERT INTO mydatabase.table VALUES (" + msg.payload.decode("utf-8") + "," + datetime + ");"
elif msg.topic.startswith("topic2/"):
insertStatement += "INSERT INTO mydatabase.table1 VALUES (" + msg.payload.decode("utf-8") + "," + datetime + ");"
elif msg.topic.startswith("topic3/")
insertStatement += "INSERT INTO mydatabase.table2 VALUES (" +msg.payload.decode("utf-8") + "," + datetime + ");"
elif msg.topic.startswith("messages"):
insertStatement += "INSERT INTO mydatabase.table3 VALUES ('" + msg.topic + "'," + msg.payload.decode("utf-8") + "," + datetime + ");"
else:
return
insertcounter +=1
if(insertCounter > 1000):
for result in cursor.execute(insertStatement, multi=True):
print result.row_count # i changed it to result
globaland string formatting of SQL statements... Why do you need to define these as global rather than attributes?