红联Linux门户
Linux帮助

Ubuntu python安装使用sqlalchemy

发布时间:2017-06-11 00:33:57来源:linux网站作者:oO维尼熊Oo
1.安装 sqlalchemy
pip install sqlalchemy
 
2.安装mysql-connector
下载地址:http://download.csdn.net/download/clean_water/9679100
解压后执行指令:
sudo python setup.py install
 
安装好后,测试下:
from sqlalchemy import Column,INTEGER, String, create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
# 创建对象的基类:
Base = declarative_base()
# 定义User对象:
class User(Base):
# 表的名字:
__tablename__ = 'user'
# 表的结构:
id = Column(INTEGER, primary_key=True,autoincrement=True)
name = Column(String(20))
# 初始化数据库连接:
engine = create_engine('mysql+mysqlconnector://root:password@localhost:3306/test')
# 创建DBSession类型:
DBSession = sessionmaker(bind=engine)
# 创建session对象:
session = DBSession()
# 创建新User对象:
new_user = User(name='Bob')
# 添加到session:
session.add(new_user)
# 提交即保存到数据库:
session.commit()
# 关闭session:
session.close()
 
执行一下,一切OK.
Ubuntu python安装使用sqlalchemy
 
本文永久更新地址:http://www.linuxdiyf.com/linux/31410.html