码迷,mamicode.com
首页 > 数据库 > 详细

python-连接数据库

时间:2016-02-02 17:47:50      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:

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()

python-连接数据库

标签:

原文地址:http://www.cnblogs.com/xiaojiayu/p/5177821.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!