简体   繁体   中英

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

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

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM