'Can't insert into table if table already exists

So I'm trying to insert a class variable into a mysql database and I'm having problems.

mysql.connector.errors.ProgrammingError: 1050 (42S01): Table 'ordertable' already exists

This message pops up when i try to insert values into a table even when i know the table exists.

order.py

import tkinter
from tkinter import *
import connection
import mysql.connector
class MenuWindow():
def init(self):
    db = mysql.connector.connect(host="localhost",user="root", passwd="", database = "pizza")
    mycursor =db.cursor()

    orderData = [(None, self.varTotal.get())]

    for element in orderData:
        mycursor.execute("INSERT INTO ordertable (orderid,total) VALUES (?,?)", element)
    db.commit()

The table is created in this file

connection.py

def get_connection():
db = mysql.connector.connect(host="localhost",user="root", passwd="", database = "pizza")

mycursor = db.cursor()

mycursor.execute("CREATE TABLE orderTable (orderid INT AUTO_INCREMENT PRIMARY KEY, total INT)")


Solution 1:[1]

The error message does not complain about the insert. It complains about the create, because connection.py attempts to create the table when it already exists.

You only need to create the table exactly once, you do not need to create it whenever you reconnect.

Remove the line of

mycursor.execute("CREATE TABLE orderTable (orderid INT AUTO_INCREMENT PRIMARY KEY, total INT)")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Lajos Arpad