Skip to content

Instantly share code, notes, and snippets.

@tschm
Last active August 29, 2015 14:23
Show Gist options
  • Save tschm/b9d65339711e5ac82f6e to your computer and use it in GitHub Desktop.
Save tschm/b9d65339711e5ac82f6e to your computer and use it in GitHub Desktop.
Little engine for Python
import logging
import pandas as pd
class Engine(object):
def __init__(self, engine):
self.__engine = engine
def read(self, table, index_col):
logging.info('SELECT * FROM {0}'.format(table))
return pd.read_sql(sql='SELECT * FROM {0}'.format(table), con=self.__engine, index_col=index_col)
def write(self, frame, table, if_exists="replace"):
logging.debug("Write to table {0}".format(table))
assert pd.notnull(frame.index.name), "Make sure the index of your frame has a name!"
frame.to_sql(name=table, con=self.__engine, if_exists=if_exists, index=True, index_label=frame.index.name)
@property
def tables(self):
return self.__engine.table_names()
if __name__ == '__main__':
from sqlalchemy import create_engine
engine = Engine(create_engine('sqlite:///:memory:', echo=False))
frame = pd.DataFrame(index=[0, 3, 5], columns=["A", "B"], data=[[2, 3], [10, 11], [5, 6]])
frame.index.name="index"
engine.write(frame, "table_a")
print(frame)
print(engine.read("table_a", index_col="index"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment