1

After the connection has been started there's a while True: and that prohibites the press of the "Quit" button to exit the software.

import PySimpleGUI as sg
import pyodbc
import time

sg.theme('DarkBlue')   

layout = [  [sg.Text('Welcome to the SQL Availability Checker.')],
            [sg.Text('Please insert the name of the Database Server')], 
            [sg.Input(key='server_name')],
            [sg.Text('Please insert the name of the Database')], 
            [sg.Input(key='db_name')],
            [sg.Text('Please insert the name of the Username to conntect to the database')], 
            [sg.Input(key='Username')],
            [sg.Text('Please insert the password for the Username to conntect to the database')], 
            [sg.Input(key='password')],
      lp. :)      [sg.Button('Connect'), sg.Button('Quit')] ,
            [sg.Text(text="Output")],
            [sg.Multiline(size=(60,15), font='Courier 8', expand_x=True, expand_y=True, write_only=True,
                reroute_stdout=True, reroute_stderr=True, echo_stdout_stderr=True, autoscroll=True, auto_refresh=True)]
                      ]
# Create the Window
window = sg.Window('SQL Availability Checker', layout)
# Event Loop to process "events" and get the "values" of the inputs
while True:
    event, values = window.read()
    if event == sg.WIN_CLOSED or event == 'Quit': # if user closes window or clicks cancel
        break
    
    if event in ('Connect'):
            while True:
                trys = 0
                server_name = values['server_name']
                db_name = values['db_name']
                Username = values['Username']
                password = values['password']
                trys += 1
                print("This is try " + str(trys) + '!')
                print("Connection establishment is starting...")

                conn = pyodbc.connect(
                    'DRIVER={ODBC Driver 17 for SQL Server};'
                    'SERVER=' + server_name + ';'
                    'DATABASE=' + db_name + ';'
                    'UID=' + Username + ';'
                    'PWD=' + password
                )
                time.sleep(0.5)

                if conn:
                    time.sleep(0.5)
                    print("The connection was established sucessfully!")
                    cursor = conn.cursor()

                    time.sleep(0.5)
                    print("Data write in is starting...")
                    # Create a test database
                    try:
                        cursor.execute('''CREATE TABLE test_users
                                    (id INT PRIMARY KEY NOT NULL, 
                                    name VARCHAR(255) NOT NULL,
                                    age INT NOT NULL);''')
                        time.sleep(0.5)
                        print("Table test_users created successfully!")

                        # Add some random content to the test_users table
                        for i in range(5):
                            cursor.execute("INSERT INTO test_users (id, name, age) \
                                        VALUES (" + str(i) + ", 'user" + str(i) + "', " + str(10 + i) + ")")
                    except:
                        time.sleep(0.5)
                        print("Table test_users already exists!")

                    # Create another example table
                    try:
                        cursor.execute('''CREATE TABLE test_items
                                    (id INT PRIMARY KEY NOT NULL,
                                    name VARCHAR(255) NOT NULL,
                                    price REAL NOT NULL);''')
                        time.sleep(0.5)
                        print("Table test_items created successfully!")
                                # Add some random content to the test_items table
                        for i in range(5):
                            cursor.execute("INSERT INTO test_items (id, name, price) \
                                        VALUES (" + str(i) + ", 'item" + str(i) + "', " + str(100 + i) + ")")
                            
                    except:
                        time.sleep(0.5)
                        print("Table test_items already exists!")

                    # Save and close the connection to the database
                    conn.commit()
                    conn.close()
                    time.sleep(0.5)
                    print("Connection was closed sucessfully!")
                
                time.sleep(0.5)
                print("Connection establishment is starting...")

                conn = pyodbc.connect(
                    'DRIVER={ODBC Driver 17 for SQL Server};'
                    'SERVER=' + server_name + ';'
                    'DATABASE=' + db_name + ';'
                    'UID=' + Username + ';'
                    'PWD=' + password
                )

                if conn:
                    time.sleep(0.5)
                    print("The connection was established sucessfully!")
                    cursor = conn.cursor()
                    time.sleep(0.5)
                    print("Data dropping is starting...")
                    # Drop both test tables
                    try:
                        cursor.execute('''DROP TABLE test_users;''')
                        time.sleep(0.5)
                        print("Table test_users dropped successfully!")
                    except:
                        time.sleep(0.5)
                        print("Table test_users doesn't exist!")

                    try:
                        cursor.execute('''DROP TABLE test_items;''')
                        time.sleep(0.5)
                        print("Table test_users dropped successfully!")
                    except:
                        time.sleep(0.5)
                        print("Table test_items doesn't exist!")
                    time.sleep(1)

                    # Save and close the connection to the database
                    conn.commit()
                    conn.close()
                    time.sleep(0.5)
                    print("The connection was closed sucessfully!")
                    time.sleep(1)
                else:
                    time.sleep(0.5)
                    print("The connection attempt wasn't sucessful. The MSSQL server is either not running or does not exist.")

window.close()

Hi I'm pretty new to python and have a bit of trouble with my first script. I want to make a SQL Availability Checker Tool and it already works more or less. Now, I added a GUI with PySimpleGui

I tried reading into multiprocessing and multi threading but didn't get how I had to implement into my script. I have no idea how to change the script to a state where I'm able to press the "Quit" button after making a connection to a database.

I am very sorry if my code seems messy or something like that.

Thank you very much for your he.

Wandi
  • 11
  • 1
  • How would you ever get back to `window.read()` to handle the next event once you enter the nested loop? Put differently, most GUI systems don't want you to sleep when responding to an event; that either means that you have to split the event handler that _would_ sleep into two handlers (that might consult the system clock) or that you have to use another thread to do the sleeping (with all the concomitant synchronization issues). – Davis Herring Jan 25 '23 at 10:14
  • Thanks, I've found another thread with your help. I'll try the answer in this [thread](https://stackoverflow.com/questions/23100704/running-infinite-loops-using-threads-in-python). Thank you very much. :) – Wandi Jan 25 '23 at 10:30
  • A comma missed in `if event in ('Connect'):`, so it will be always failed and not executed for this button. – Jason Yang Jan 25 '23 at 10:42
  • Please trim your code to make it easier to find your problem. Follow these guidelines to create a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). – Community Jan 25 '23 at 10:56

0 Answers0