Select SQLite database table to export data to CSV file by using Pandas DataFrame
On click of a button the file browser is displayed to connect to any SQLite database file. Based on the list of available tables in the database, a set of Radio buttons are displayed for user selection. Using the selected table name the read_sql() method is used to create a Pandas Dataframe. One Save As dialog box is shown to user to save the data as csv file using the Pandas to_csv() method.
1. Importing Required Libraries
from sqlalchemyimport create_engine, text# For database connection and SQL executionfrom sqlalchemy.excimport SQLAlchemyError# To handle SQL exceptionsimport tkinteras tk# GUI libraryfrom tkinterimport filedialog# File dialog for opening and saving filesimport pandasas pd# Data manipulation library
pandas: A library for manipulating and exporting data (e.g., to CSV).
2. Defining Global Variables
my_font = ['Arial', 14, 'normal']# Font style for radio buttonsradio_buttons = []# List to track dynamically created radio buttonsmy_conn = None# Database connection object
my_font: Specifies the font style for dynamically created radio buttons.
defmy_selected():
global my_conn
selected_table = my_var.get() # Get selected table name from the radio buttonif not selected_table:
print("No table selected.")
return# Open file dialog to save the CSV file
file_path = filedialog.asksaveasfilename(
defaultextension=".csv",
filetypes=[("CSV files", "*.csv"), ("All files", "*.*")]
)
if not file_path:
print("File save cancelled.")
returntry:
query = f"SELECT * FROM {selected_table}"
df = pd.read_sql(query, my_conn) # Load table into a Pandas DataFrame
df.to_csv(file_path, index=False) # Save DataFrame as CSVprint(f"Table '{selected_table}' exported successfully to {file_path}")
except Exception as e:
print("An error occurred:", e)
my_selected(): Triggered when a table is selected ( user clicks a radio button) ; fetches and exports its data to a CSV file.
pd.read_sql(): Reads the SQL query results into a Pandas DataFrame.
tk.Label: Adds labels for headers and displaying the database path.
tk.Button: Creates a button for initiating database connection.
my_w.mainloop: Starts the Tkinter event loop to display the GUI.
Export user selected SQLite Table to CSV with Python Tkinter and Pandas #sqlite #csv #DataExport
from sqlalchemy import create_engine, text
from sqlalchemy.exc import SQLAlchemyError
import tkinter as tk
from tkinter import filedialog
import pandas as pd
# Global variables
my_font = ['Arial', 14, 'normal']
radio_buttons = [] # List to track radio buttons
my_conn = None
# Function to connect to SQLite database
def my_connect(type):
global my_conn, radio_buttons
f_types = [('All Files', '*.*'),
('Text Document', '*.txt'),
('Database files', "*.db")]
if type == 'existing':
file = filedialog.askopenfilename(filetypes=f_types)
else:
file = filedialog.asksaveasfilename(filetypes=f_types, defaultextension=".db",)
try:
if file: # Ensure a file was selected
# Update the label with the selected file path
l1_path.config(text=f"Connected to: {file}", fg="green")
# Connect to the SQLite database
file1 = 'sqlite:///' + file
my_conn = create_engine(file1).connect()
# Fetch table names SQL query
q="SELECT name FROM sqlite_master WHERE type = 'table'"
r_set = my_conn.execute(text(q))
table_names = [row[0] for row in r_set]
# Remove any previously created radio buttons
for button in radio_buttons:
button.destroy()
radio_buttons.clear()
# Create new radio buttons based on table names
for i, t_name in enumerate(table_names):
rd1 = tk.Radiobutton(my_w, text=t_name, variable=my_var, value=t_name,
command=my_selected, fg="blue", bg="light gray", font=my_font,
selectcolor="yellow", activebackground="light blue",
activeforeground="yellow", indicatoron=0, width=15,
compound="left")
rd1.grid(row=3 + i, column=0, columnspan=4, sticky="w", padx=10, pady=5)
radio_buttons.append(rd1)
else:
l1_path.config(text="No file selected", fg="red")
except SQLAlchemyError as e:
error = str(e.__dict__['orig'])
l1_path.config(text=f"Error: {error}", fg="red")
print("Error:", error)
# Function to handle table selection
def my_selected():
global my_conn
selected_table = my_var.get() # from Radio button selection
if not selected_table:
print("No table selected.")
return
# Open file dialog to save the CSV file
file_path = filedialog.asksaveasfilename(
defaultextension=".csv",
filetypes=[("CSV files", "*.csv"), ("All files", "*.*")]
)
if not file_path:
print("File save cancelled.")
return
try:
# Fetch data from the selected table and create a DataFrame
query = f"SELECT * FROM {selected_table}"
df = pd.read_sql(query, my_conn) # Pandas DataFrame created
# Export DataFrame to CSV
df.to_csv(file_path, index=False) # from dataframe to CSV
print(f"Table '{selected_table}' exported successfully to {file_path}")
except Exception as e:
print("An error occurred:", e)
# Main application window
my_w = tk.Tk()
my_w.geometry("800x500") # Width & height of window
my_w.title("plus2net SQLite Connector") # title of window
my_var = tk.StringVar() # to store table name
# Header
font1 = ('Times', 20, 'bold') # higher font for heading
l0 = tk.Label(my_w, text='plus2net.com SQLite Connector', font=font1)
l0.grid(row=0, column=0, columnspan=4, pady=10)
# Path display label
l1_path = tk.Label(my_w, text='', font=('Arial', 12), wraplength=700, anchor="w", justify="left")
l1_path.grid(row=1, column=0, columnspan=4, sticky="w", pady=5, padx=10)
# Connect button
b1 = tk.Button(my_w, text='Browse & Connect', width=20, command=lambda: my_connect('existing'))
b1.grid(row=2, column=0, columnspan=4, pady=10)
# Start Tkinter main loop
my_w.mainloop()