Skip to content

Instantly share code, notes, and snippets.

@ojos
Last active August 29, 2015 14:15
Show Gist options
  • Save ojos/f7290324daf377af303f to your computer and use it in GitHub Desktop.
Save ojos/f7290324daf377af303f to your computer and use it in GitHub Desktop.
# MySQLdbの場合
#
import MySQLdb
connection = MySQLdb.connect(host='192.168.59.103', db='hoge_db', user='hoge_user', passwd='hoge_pw', charset='utf8')
cursor = connection.cursor()
cursor.execute('select * from foo_bar')
result = cursor.fetchall()
for row in result:
print row
cursor.close()
connection.close()
# sqlalchemyの場合
#
from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base
DATABASE = 'mysql://hoge_user:[email protected]/hoge_db'
engine = create_engine(DATABASE, encoding='utf-8')
db_session = scoped_session(sessionmaker(autocommit=False,
autoflush=False,
bind=engine))
Base = declarative_base()
Base.query = db_session.query_property()
class Hoge(Base):
__tablename__ = 'foo_bar'
id = Column(String(16), nullable=False, primary_key=True)
ip_address = Column(String(15), nullable=False, unique=True)
cur = db_session.query(Hoge).all()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment