Ejemplo n.º 1
0
def __createBuilder( target, source, env ) :
    # create the database connection and set the transaction
    engine      = None
    metadata    = None
    connect     = None
    transaction = None
    
    try :
        engine      = sqlalchemy.create_engine(env["connection"], echo = env.get("DATABASE_VERBOSE", False) )   
        metadata    = sqlalchemy.MetaData()
        connect     = engine.connect()
        transaction = sqlalchemy.sessionmaker(autocommit=False)
    except Exception, e :
        raise SCons.Errors.StopError( e )
Ejemplo n.º 2
0
    def connect(self):
        try:
            engine = create_engine(
                "mysql+pymysql://%(user)s:%(pass)s@%(host)s:%(port)s/%(name)s" %
                {
                    "host": urllib.quote(
                        self.db_host), "port": self.db_port, "name": urllib.quote(
                        self.db_name), "user": urllib.quote(
                        self.db_user), "pass": urllib.quote(
                        self.db_pass)}, convert_unicode=True)

            table_map = TableMap()
            table_map.mapping(engine)
            Session = sessionmaker(bind=engine)
            return Session()
        except Exception:
            raise
Ejemplo n.º 3
0
CONN_STR = '…'
engine = create_engine('sqlite:////home/friend/01-github/dw2ed/bd/python/load_existing_db/companies_1000.db')
metadata = MetaData()
insp = inspect(engine)
print(insp.get_table_names())

companias = Table('compania', metadata, 
  sa.Column("n", sa.String(50), primary_key=True),
  sa.Column("nome", sa.String(50)),
  sa.Column("dominio", sa.String(50)),
  sa.Column("ano", sa.String(50)),
  sa.Column("industria", sa.String(50)),
  sa.Column("tamanho", sa.String(50)),
  sa.Column("localizacao", sa.String(50)),
  sa.Column("pais", sa.String(50)),
  sa.Column("linkedin", sa.String(250)),
  sa.Column("empregados_atual", sa.Integer),
  sa.Column("empregados_total", sa.Integer)
)

with engine.connect() as conn:

    query = 'select * from compania'
    for row in conn.execute(query):
        print(row)

Session = sa.sessionmaker(bind=engine)
session = Session()

Ejemplo n.º 4
0
from sqlalchemy import create_engine
from sqlalchemy import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from config import SQLALCHEMY_DATABASE_URI

engine = create_engine(SQLALCHEMY_DATABASE_URI, convert_unicode=True)
db_session = scoped_session(sessionmaker(autocommit=False,
                                         autoflush=False,
                                         bind=engine))

Base = declarative_base()
Base.query= db_session.query_property()

def init_db():
    from app.models import Video
    from app.models import User
    from app.models import Comment
    from app.models import News
    from app.models import Histroy
    Base.metadata.create_all(bind=engine)
Ejemplo n.º 5
0
#!/usr/bin/python3
"""
=========================================================================
script that prints the first State object from the database hbtn_0e_6_usa
=========================================================================
"""

from model_state import Base, State
from sqlalchemy import create_engine
from sqlalchemy import sessionmaker
import sys

if __name__ == "__main__":
    engine = create_engine('mysql+mysqldb://{}:{}@localhost/{}'.format(
        sys.argv[1], sys.argv[2], sys.argv[3]),
                           pool_pre_ping=True)

    the_session = sessionmaker(bind=engine)
    session = the_session()

    el_primerito = session.query(State).first()
    if el_primerito is None:
        print("Nothing")
    else:
        print("{}: {}".format(el_primerito.id, el_primerito.name))
#!/usr/bin/python3
''' Create the state model from table states '''

from sqlalchemy import create_engine, sessionmaker
from states import State

if __name__ == '__main__':
    engine = create_engine("mysql+mysqldb://root:root@localhost/hbtn_0e_6_usa")

    Session = sessionmaker(engine)
    session = Session()

    states = session.query(State).order_by(State.id)

    for state in states:
        print(state.name)
Ejemplo n.º 7
0
import OS
from sqlalchemy import create_engine
from sqlalchemy import scoped_session,sessionmaker

engine = create_engine(os.getenv("DATABASE_URL"))
db = scoped_session(sessionmaker(bind = engine))

def main():
    flights = db.execute("SELECT origin, destination, duration FROM flights").fetchall()
    for flight in flights:
        print(f"{flight.origin} to {flight.destination}, {flight.duration} minutes")

if __name__ = "__main__":
    main()
Ejemplo n.º 8
0
import numpy as np
import pandas.DataFrame

db = create_engine('sqlite:///forjar.db')

metadata = MetaData(db)

users = Table('Users', metadata, autoload=True)

s = users.select()
rs = s.execute()

campaign_to_num = {'TW': 1, 'RE': 2, 'FB': 3, 'PI': 4}

campaigns = []

Session = sessionmaker(bind=some_engine)
session = Session()
q = session.query(users)

x = np.array(campaigns)

n, bins, patches = plt.hist(x, bins=4, label=['TW', 'RE', 'FB', 'PI'])

plt.xlabel('Campaigns ')
plt.ylabel('Number')
plt.title('Histogram of Users from Different Campaigns')
plt.grid(True)
plt.show()

print x
from sqlalchemy import create_engine
from sqlalchemy import sessionmaker
from database_setup import Base, Restaurant, MenuItem

# Point the DB we want to comunicate
engine = create_engine('sqlite:///restaurantmenu.db')

# Bind engine to `Base` class.
# Connects our classes definitions to tables in the DB
Base.metadata.bind = engine

# Create a session object to connect to the DB
DBSession = sessionmaker(bind=engine)
session = DBSession()

# New row in `restaurant` table (instance of our `Restaurant` class)
myRestaurant = Restaurant(name='Pizza Palace')

# Add changes to staging zone
session.add(myRestaurant)

# New row in `menu_item` table (instance of our `MenuItem` class).
# Includes a Foreign key reference
cheese_pizza = MenuItem(name='Cheese Pizza',
                        description='Made with four types of cheese!',
                        course='Entree',
                        price='$8.99',
                        restaurant=myRestaurant)

# Add changes to staging zone
session.add(cheese_pizza)
Ejemplo n.º 10
0
 def __init__(self):
     self.engine = create_engine('sqlite://')
     self.conn = self.engine.connect()
     Session = sessionmaker(bind=self.engine)
     self.session
Ejemplo n.º 11
0
users = Table('Users', metadata, autoload=True)

s = users.select()
rs = s.execute()

campaign_to_num = {
	'TW' : 1,
	'RE' : 2,
    'FB' : 3,
    'PI' : 4
}

campaigns = []


Session = sessionmaker(bind=some_engine)
session = Session()
q = session.query(users)




x = np.array(campaigns)


n, bins, patches = plt.hist(x,bins=4,label=['TW', 'RE', 'FB','PI'])


plt.xlabel('Campaigns ')
plt.ylabel('Number')
plt.title('Histogram of Users from Different Campaigns')