-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathPy_Sql_Alchemy_Class.py
More file actions
64 lines (48 loc) · 2.06 KB
/
Py_Sql_Alchemy_Class.py
File metadata and controls
64 lines (48 loc) · 2.06 KB
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
63
64
import pandas as pd
import sqlalchemy
from sqlalchemy.engine import URL
class DB_Table_Ops:
def __init__(self, driver='{SQL Server}',
server='localhost\SQLEXPRESS',
database='master',
trusted_connection='yes'):
connection_string = f'DRIVER={driver};SERVER={server};'
connection_string += f'DATABASE={database};'
connection_string += f'TRUSTED_CONNECTION={trusted_connection}'
# create sqlalchemy engine connection URL
connection_url = URL.create(
"mssql+pyodbc",
query={"odbc_connect": connection_string})
self.engine = sqlalchemy.create_engine(connection_url)
def table_exists(self, table_name):
qs = f'''select schema_name(t.schema_id) as schema_name,
t.name as table_name
from sys.tables t
order by schema_name,
table_name;'''
with self.engine.connect() as conn:
cursor = conn.execute(sqlalchemy.text(qs))
table_exists = [t for t in cursor if table_name == t[1]]
return bool(table_exists)
def create_table(self, schema_str):
table_name = schema_str.split()[2]
if self.table_exists(table_name):
return
with self.engine.connect() as conn:
conn.execute(sqlalchemy.text(schema_str))
def drop_table(self, table_name):
if not self.table_exists(table_name):
return
cs = f'''DROP TABLE {table_name}'''
with self.engine.connect() as conn:
conn.execute(sqlalchemy.text(cs))
def insert_df_to_table(self, df, table_name):
df.to_sql(table_name, self.engine,
if_exists="append", index=False)
def query_to_df(self, query_string):
with self.engine.connect() as conn:
df = pd.read_sql_query(query_string, conn)
return df
def update_DB(self, command):
with self.engine.connect() as conn:
conn.execute(sqlalchemy.text(command))