python-连接数据库
2016-02-02 16:12
411 查看
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测试用例覆盖率工具coverage教程(命令行工具)(译)
- 一个可能有用的Python+MQL4混合编程网址
- python 配置github项目配置
- python 笔记 lambda
- python 笔记 lambda
- Python第三讲选择和循环
- Python特殊语法这之:filter、map、reduce、lambda
- python 容器
- ORA-01031: insufficient privileges
- python中的with与@contextlib.contextmanager
- python 函数学习
- Python成长之路第一篇(3)_初识字典
- Python深复制浅复制or深拷贝浅拷贝
- python 笔记 文件操作
- python 笔记 文件操作
- Python内置模块(一)
- The Basics of Numpy
- The Basics of Numpy
- python环境
- Python 第十一章 常用第三方模块