forked from WilliamQLiu/python-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsqlorm.py
More file actions
78 lines (57 loc) · 2.29 KB
/
sqlorm.py
File metadata and controls
78 lines (57 loc) · 2.29 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
65
66
67
68
69
70
71
72
73
74
75
import urllib
import pyodbc
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
import pandas as pd
# SQLAlchemy SETUP
params = urllib.quote_plus('DRIVER={SQL Server};SERVER=myserver;DATABASE=mydb;UID=sa;PWD=mypassword')
engine = create_engine("mssql+pyodbc:///?odbc_connect=%s" % params)
Base = declarative_base()
Session = sessionmaker(bind=engine)
class LookupTable(Base):
"""
LookupTable is the Python object that represents the Lookup Table used in the database.
"""
__tablename__ = 'iCarolLookup'
cscid = Column(String(50), primary_key=True)
value = Column(String(512))
if __name__ == '__main__':
# SETUP
Base.metadata.create_all(engine)
print type(Base)
#session = Session()
# Let's see what is in the current Table, we want a 'snapshot' of this Table
#current_table = session.query(LookupTable).all()
#for row in current_table:
# print row.cscid, row.value # Peak at the dataset
# We want to convert this query into a Pandas DataFrame for checking later
#query = session.query(LookupTable)
#data_records = [rec.__dict__ for rec in query.all()]
#current_df = pd.DataFrame.from_records(data_records)
#print raw_df.columns # Index([u'_sa_instance_state', u'cscid', u'value'], dtype='object')
#print current_df
pdsql = pd.io.sql.SQLDatabase(engine)
current_df = pd.read_sql("SELECT * FROM iCarolLookup", con=engine)
print current_df
# Get csv file from iCarol to import into our Database Table
#new_df = pd.DataFrame.from_csv('')
test_dict = {
'2': 'Testing2',
'3': 'Testing3'
}
test_df = pd.DataFrame({'cscid': ['2', '3', '4'],
'value': ['Hello', 'World', 'Liu']})
print test_df
# Compare the two dataframes, see what fields have changed
# Write new df to SQL
test_df.to_sql(name="iCarolLookup", if_exists='append', index=False, con=engine)
# How to write data to the Database Table
#test_kvpair = LookupTable(cscid='1', value='Testing')
#session.add(test_kvpair)
#try:
# session.commit()
# print "Session Committed"
#except:
# print "Error with committing session"
# raise