Python - MySQLdb - 未插入表中的数据

时间:2015-10-01 09:41:34

标签: python mysql sql-insert mysql-python

我正在尝试使用MySQLdb将数据输入MySQL表,但它没有将数据插入表中。 我的代码是:

      try:
            db = MySQLdb.Connect("127.0.0.1","root","root","bank")
            cursor = db.cursor()
            cursor.execute("SELECT max(account_number) from pybank")
            results = cursor.fetchall()
            for row in results:
                self.account_number = row[0]
            sql = "INSERT INTO pybank(account_number,user_name, user_age, user_dob, amount) VALUES(%d,'%s',%d,'%s',%d)" %(self.account_number + 1,self.user_name, self.user_age, self.user_dob, self.total_amount)
            print(sql)

            cr = db.cursor()
            cr.execute(sql)
            db.commit()
            print("Your have successfully created your account")
            self.getAccountDetails()
        except:
            db.rollback()
            print("Your account is not created !!!! ")
            print
            print("Please try again")

1 个答案:

答案 0 :(得分:2)

你在VALUES附近的SQL中输入错误,你也应该使用占位符:

cursor = db.cursor()
cursor.execute("INSERT INTO pybank (account_number,user_name, user_age, user_dob, amount) VALUES (%s, %s, %s, %s, %s)", (self.account_number + 1, self.user_name, self.user_age, self.user_dob, self.total_amount))