Python Forum

Full Version: Insert 0 values in database
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have this python code. I am using tk and pyodbc. when I have run this code, it inserts 0 value in user_id column in the database even I haven't enter anything in name_entry entry. how to handle same this problems.
in database: I have created tables and this is the code:
CREATE TABLE test3
( entry_id int IDENTITY(1,1) PRIMARY KEY,
 user_id int  not null,
    user_name VARCHAR  (25) not NULL,
);
and here are python code

   id_id=IntVar()
   id_entry=tk.Entry(root, textvariable=id_id)

   name_name=StringVar()
   name_entry=tk.Entry(root,textvariable=name_name)

   get_id=id_entry.get()
   get_name=name_entry.get()
   cursor.execute("""INSERT INTO test3 (user_id, user_name) VALUES (?,?)""", get_id, get_name)
any help would be greatly appreciated
[Image: Xax1I.png]
missing commit
(Oct-26-2020, 10:19 AM)Larz60+ Wrote: [ -> ]missing commit

no I do not just I want to make the code short for question
here are the all codes

import tkinter as tk
from tkinter import *
import pyodbc
root = tk.Tk()

id_id=IntVar()
id_entry=tk.Entry(root, textvariable=id_id)
id_entry.grid()

name_name=StringVar()
name_entry=tk.Entry(root,textvariable=name_name)
name_entry.grid()

get_id=id_entry.get()
get_name=name_entry.get()
conn = pyodbc.connect('Driver={ODBC Driver 17 for SQL Server};'
                      'Server=XXXX\SQLEXPRESS;'
                      'Database=test1;'
                      'Trusted_Connection=yes;')
cursor = conn.cursor()
cursor.execute("""INSERT INTO test3 (user_id, user_name) VALUES (?,?)""", get_id, get_name)
conn.commit()
conn.close()
root.mainloop()
the code to execute the insert will execute upon instantiation.
This cannot work as nothing has been entered into the entry widget at this point.

you need to bind the entry to a callback routine, and execute the database insert within the callback.
Here's a 'how to' for this: https://www.delftstack.com/howto/python-...n-tkinter/
I want to say thank you to all who had replied, and I want to give you some update, it may helps someone who has same my issue. I have added try: and except and this was solving my problem:

try:
            cnn.autocommit = False
            cursor.execute("""INSERT INTO  (A) values (?)""",AA)
        except pyodbc.DatabaseError as err:
            print(err)
            cnn.rollback()
        else:
            cnn.commit()
        finally:
            cnn.autocommit = True
            cnn.commit()
            cnn.close()