Column count doesn't match value count at row 1 error displayed using python

Viewed 347

I am a beginner in python. when i insert the record into the database. records are not added. I have a two columns in the database id,name. id set in mysql auto increment.

from tkinter import *
import mysql.connector  # Importing Connector package

def Ok():
    result = e1.get()

    mysqldb=mysql.connector.connect(host="localhost",user="root",password="",database="empdb")#established connection between your database
    mycursor=mysqldb.cursor()

    try:
   mycursor.execute("insert into records values(%s)", (result,))
   mysqldb.commit()
   print('Record inserted successfully...')

  except Exception as e:
   print(e)
 
    mysqldb.rollback()
    mysqldb.close()

   raise Exception("Sorry, no numbers below zero")

root = Tk()
root.title("Employee Salary Calculation System")
root.geometry("300x400")

global e1

Label(root, text="Employee Name").place(x=10, y=10)

e1 = Entry(root)
e1.place(x=100, y=10)


Button(root, text="Cal", command=Ok ,height = 1, width = 3).place(x=10, y=150)

root.mainloop()

Error displayed

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\kobinath\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 1883, in __call__
    return self.func(*args)
  File "C:/Users/kobinath/PycharmProjects/pythonProject4/employee.py", line 20, in Ok
    raise Exception("Sorry, no numbers below zero")
Exception: Sorry, no numbers below zero

I got the error above.

2 Answers

If you are trying to catch an exception in python, you can use the following code:

try:
    x = int(input('Enter a number'))
except Exception as e:
    print (e)

This will help you find out what kind of error is occurring.

Looks like you are having a problem trying to insert data into a table.

Let us assume I have a table named customers and it has two columns name, and address, then I can write the following statements to insert a record into the table.

sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"

val = ("John", "Highway 21")

mycursor.execute(sql, val)

mydb.commit()

Then give commit to commit the record. If you have more than one column, it is important that you give those details in your INSERT statement.

In your code, this line

raise Exception("Sorry, no numbers below zero")

is executed anyway. Please check what you want to do and fix it.

But the reason you cannot insert a record is because of this:

mycursor.execute("insert into records values(result)")

Note that the whole string inside quote is executed as a SQL statement. Are you sure "result" is something valid in your context? This may have the MySQL raised an error. I believe what you mean is this:

mycursor.execute("insert into records values(%s)", (result,))
Related