I have searched for this, and no matter what I try, I cannot get records to insert into a MySQL table in Python. I have done a commit, but still nothing is committed. Here is the code that I have now. Thanks for any insight you can offer.
commentauthor = comment.author
theauthor = commentauthor.name
try:
mydb = mysql.connector.connect(
host="localhost",
user="user",
passwd="pass",
database="mydb"
)
readcursor = mydb.cursor(buffered=True)
SQL = "SELECT * FROM atable WHERE username = '%s'" % (theauthor)
readcursor.execute(SQL)
if readcursor.rowcount == 0:
repcount = 1
else:
myresult = readcursor.fetchone()
for row in myresult:
repcount = row[1] + 1
writecursor = mydb.cursor()
if repcount == 1:
SQL = "INSERT INTO atable (username, usercount) VALUES ('%s', %d)" % (theauthor, repcount)
else:
SQL = "UPDATE atable SET usercount = %d WHERE username = '%s'" % (repcount, theauthor)
writecursor.execute(SQL)
mydb.commit
print(SQL)
SQL = "SELECT * FROM atable WHERE username = '%s'" % (theauthor)
readcursor.execute(SQL)
print(SQL)
acount = readcursor.fetchone()[1]
print(acount)
readcursor.close
writecursor.close
mydb.close
except:
print(SQL)
print("Error: unable to fetch data")
Immediately after the INSERT, the next SELECT that is done shows a '1' for the value (like it did insert the data), but no data is actually in the table. Using a MySQL admin GUI, the table is empty, and running the same code above a second time returns no records.
commit. Add()to it. The same applies to other calls in your code.