Search code examples
pythonmysqlpymysql

Unable to update SQL database using python Pymysql


I'm trying to create a class to automatically generate customer objects which would automatically get updated in the customer table in Mysql.

While i'm able to successfully generate customers, i'm not seeing the updated results in localhost/phpmyadmin.

from itertools import count
import pymysql

db = pymysql.connect('localhost','root','',db = 'customers')

cursor = db.cursor()

class customer():
    _ids = count(0)

    def __init__(self,User,Password,Wallet):
        self.ID = next(self._ids)
        self.User = User
        self.Password = Password
        self.wallet = Wallet

        insert = '''INSERT INTO customer(ID,Username,Password,Wallet) values ('%s','%s','%s','%s');'''%(self.ID,self.User,self.Password,self.wallet)

        conn = pymysql.connect('localhost','root','',db = 'customers')
        inscursor = conn.cursor()
        conn.commit()

Python doesnt seem to raise any error or exceptions as well.

KJ


Solution

  • You have to execute before commit.

    with connection.cursor() as cursor:
        # Create a new record
        sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
        cursor.execute(sql, ('webmaster@python.org', 'very-secret'))
    
    # connection is not autocommit by default. So you must commit to save
    # your changes.
    connection.commit()
    

    https://github.com/PyMySQL/PyMySQL#example