python-连接数据库

from sqlalchemy import create_engine,text,Column,Integer,String,Sequence
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker


Base = declarative_base()


DB_CON_STR = 'mysql+mysqlconnector://root:123456@localhost/blog'
# DB_CON_STR = 'mysql+mysqlconnector://guijianliang:123456@localhost/blog'
engine =create_engine(DB_CON_STR,echo=True)

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

#eg1 via class
#res = session.query(Product).filter(Product.id==1).one()
# res = session.query(Product).filter(text("id=1")).one()


# print(res.id, res.name, res.count)

class Product(Base):
__tablename__='entries'

id = Column(Integer,Sequence('id'),primary_key=True)
name = Column(String)
count = Column(Integer)

def __repr__(self):
return "<Product(id='%d',name='%s',count='%d')>"%(self.id,self.name,self.count)

# print(res)
#eg2 via sql
sql = text("select * from entries")
res = session.execute(sql).fetchall()
print(res)
#
# for row in res:
# for col in row:
# print(col)



session.close()
posted @ 2016-02-02 16:12  xiaojiayu  阅读(208)  评论(0编辑  收藏  举报