Skip to content

Commit 7066a56

Browse files
Add files via upload
1 parent 8ccf2a4 commit 7066a56

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

gradio_add_table_to_database.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
#Add table to existing database
2+
#
3+
4+
import gradio as gr
5+
import sqlite3
6+
import pandas as pd
7+
import os
8+
9+
def add_csv_to_database(file, db_name, table_name):
10+
try:
11+
# Validate inputs
12+
if not file or not db_name or not table_name:
13+
return "Error: All inputs are required."
14+
15+
# Ensure the database name ends with .db
16+
if not db_name.endswith(".db"):
17+
db_name += ".db"
18+
19+
# Read the CSV file into a Pandas DataFrame
20+
df = pd.read_csv(file.name)
21+
22+
# Connect to the SQLite database
23+
conn = sqlite3.connect(db_name)
24+
25+
# Add the DataFrame to the database as a new table
26+
df.to_sql(table_name, conn, if_exists="fail", index=False)
27+
28+
conn.close()
29+
return f"Successfully added the table '{table_name}' to the database '{db_name}'."
30+
except ValueError as ve:
31+
return f"Error: {ve}. The table might already exist. Try using a different table name."
32+
except Exception as e:
33+
return f"Error: {e}"
34+
35+
# Gradio interface
36+
with gr.Blocks() as app:
37+
gr.Markdown("### Drag and Drop CSV to Add as Table in SQLite Database")
38+
39+
db_input = gr.Textbox(label="Database Name (e.g., 'my_database.db')", placeholder="Enter the SQLite database name")
40+
table_input = gr.Textbox(label="Table Name", placeholder="Enter the name for the new table")
41+
csv_input = gr.File(label="Upload CSV File", file_types=[".csv"])
42+
status_output = gr.Textbox(label="Status", interactive=False)
43+
44+
submit_button = gr.Button("Add CSV to Database")
45+
46+
submit_button.click(
47+
add_csv_to_database,
48+
inputs=[csv_input, db_input, table_input],
49+
outputs=[status_output]
50+
)
51+
52+
app.launch(server_name="0.0.0.0", server_port=7864)

0 commit comments

Comments
 (0)