-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenTerraDB.py
62 lines (50 loc) · 1.36 KB
/
genTerraDB.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
"""
this program will generate a new terra DB file every time you call it
Args:
none
Returns:
output: sqlite database file
"""
import os
import sqlite3
import pandas as pd
CONNECTION_OBJECT: str = "terra2023.db"
SQL_FILE: str = "terra2023.sql"
def run_query(q) -> pd.DataFrame:
"""
function to return a pandas dataframe from a query
"""
try:
with sqlite3.connect(CONNECTION_OBJECT) as conn:
# retrieve sql query output
qr: pd.DataFrame = pd.read_sql_query(q, conn)
except sqlite3.Error as ex:
print(ex)
return qr
def run_command(c) -> None:
"""
function to run sqlite command
"""
try:
with sqlite3.connect(CONNECTION_OBJECT) as conn:
# tells sqlite to autocommit any changes
conn.isolation_level = None
conn.execute(c)
except sqlite3.Error as ex:
print(ex)
# clear previous run
try:
os.remove(CONNECTION_OBJECT)
except os.error as ex_remove:
print(ex_remove)
# Read the contents of your .sql file
with open(SQL_FILE, "r", encoding="UTF-8") as input_file:
sql_script: str = input_file.read()
# Connect to your SQLite database
db = sqlite3.connect(CONNECTION_OBJECT)
cursor = db.cursor()
# Execute the SQL script
cursor.executescript(sql_script)
# Commit changes and close the connection
db.commit()
db.close()