Unable to update SQL database using python Pymysql

2.4k views Asked by At

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

2

There are 2 answers

0
Robert Moon On BEST ANSWER

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, ('[email protected]', 'very-secret'))

# connection is not autocommit by default. So you must commit to save
# your changes.
connection.commit()

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

0
Tata On

The answer is very simple. You are not running the query you are building.

You should add the row

inscursor.execute(insert) 

before conn.commit()