Skip to content

Commit 38ed0d1

Browse files
authored
Add files via upload
1 parent 7beba43 commit 38ed0d1

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

main.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import pandas as pd
2+
import sqlite3
3+
import sys
4+
import os
5+
6+
currentDir = str(os.path.basename(os.path.dirname(os.path.realpath(__file__))))#Gets current directory
7+
8+
print("----- CSV -> SQL DB -----")
9+
filePath = input(str("Insert file path to CSV file: "))#Prompts user for file path
10+
dbName = input(str("Insert name for new DB file: "))#Prompts user for new db file name
11+
conn = sqlite3.connect(currentDir + "/" + dbName+ '.db')#Creating/connecting to new DB
12+
csvData = pd.read_csv(filePath)#read file from filePath variable
13+
14+
printCSV = input(str("Print CSV contents (Y/N): "))
15+
if printCSV == "Y":
16+
print("\n=============================================")
17+
print(csvData)#print contents of csvData
18+
print("=============================================\n")
19+
print("\nCreating DB from CSV...")
20+
else:
21+
print("Creating DB from CSV...")
22+
23+
cursor = conn.cursor()#Initialize cursor (writes data to DB)
24+
cursor.execute("CREATE TABLE IF NOT EXISTS dbTable ({})".format(' ,'.join(csvData.columns)))#Create table in DB
25+
26+
for row in csvData.iterrows():
27+
sql = "INSERT INTO dbTable ({}) VALUES ({})".format(' ,'.join(csvData.columns), ','.join(["?"] * len(csvData.columns)))
28+
cursor.execute(sql, tuple(row[1]))#For rwo in CSV, insert that row's values into a new row in the DB table
29+
30+
conn.commit()#Finalize changes to DB
31+
conn.close()#Close DB connection
32+
sys.exit()#Closes program after all code has run

0 commit comments

Comments
 (0)