when I run this code I get no errors and everything seems to work but it doesn't actually write to the database. If I copy the sql string that is generated by the print function and paste it directly into a MariaDB terminal session, it works perfectly. This is the sql that is generated:
INSERT INTO msg_store (cons, prod, file) VALUES ('XXX','YYY','ZZZ');
If I change the database name or any of the required parameters, I get errors as expected. I have successfully used most of this code in other applications. I'm running it on a Raspberry Pi 4 with Python3.7
import pymysql
class C_DataBase: # Database Communication Class
def __init__(self, host_ip, db_name, user_name, password, poll_time = None):
self.ip = host_ip
self.db = db_name
self.un = user_name
self.pw = password
if poll_time is not None:
self.pt = poll_time
def connect(db):
try:
con = pymysql.connect(host=db.ip, # host
user=db.un, # username
passwd=db.pw, # password
db=db.db) # name of the data base
return con.cursor() # Open the database and return
except Exception as e:
print('DBOpenError, Failed to Connect to={}, IP={}, user={}, pw={}'.format(db.db, db.ip, db.un, db.pw))
def pub_sql(db, cons, prod, msgb):
con = connect(db)
col = "cons, prod, file"
val ="'" + cons + "','" + prod + "','" + msgb + "'"
sql = "INSERT INTO msg_store (" + col + ") VALUES (" + val + ");"
try:
rslt = con.execute(sql)
print(rslt, sql)
con.close()
except Exception as e:
print('SQLWriteError={}'.format(e))
if __name__ == '__main__':
db = C_DataBase('localhost', 'testdb', 'rpi', 'rpi') # Create and populate a database object
pub_sql(db, 'XXX', 'YYY', 'AAA') # Call the publishing function
mariaDB terminal session
;MariaDB [testdb]> INSERT INTO msg_store (cons, prod, file) VALUES ('XXX','YYY','AAA');
Query OK, 1 row affected (33.852 sec)
MariaDB [testdb]>
MariaDB [testdb]> select * from testdb.msg_store;
+------+------+---------+
| cons | prod | file |
+------+------+---------+
| ABC | DEF | message |
| ABC | DEF | message |
| XXX | DEF | message |
| XXX | YYY | ZZZ |
| XXX | YYY | AAA |
+------+------+---------+
5 rows in set (0.001 sec)
After con.execute()
you should also do con.commit()
after that you can close the connection