0

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.

2
  • 2
    You missed to call commit. Add () to it. The same applies to other calls in your code. Commented Sep 9, 2019 at 2:30
  • Doh! Thank you! I'm new to Python, and I missed that point. It works now. Appreciate your time! Commented Sep 9, 2019 at 2:33

1 Answer 1

1

Thanks to Klaus, it was due to a coding error. Works now that I did a proper call.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.