无法使用python Pymysql更新SQL数据库

时间:2015-06-15 07:57:19

标签: python mysql pymysql

我正在尝试创建一个类来自动生成客户对象,这些对象将自动在Mysql的customer表中更新。

虽然我能够成功生成客户,但我没有在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似乎也不会引发任何错误或异常。

KJ

2 个答案:

答案 0 :(得分:1)

你必须在提交前执行。

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

答案 1 :(得分:0)

答案很简单。 您没有运行您正在构建的查询。

您应该添加行

inscursor.execute(insert) 

之前conn.commit()