SQLAlchemy“采用简单的Python语言,为高效和高性能的数据库访问设计,实现了完整的企业级持久模型”。SQLAlchemy的理念是,SQL数据库的量级和性能重要于对象集合;而对象集合的抽象又重要于表和行。因此,SQLAlchmey采用了类似于Java里Hibernate的数据映射模型,而不是其他ORM框架采用的Active Record模型。不过,Elixir和declarative等可选插件可以让用户使用声明语法。

安装

pip3 install SQLAlchemy

pip3 install pymysql  #需要pymysql或者MySQLdb的支持

连接数据库

mysql+pymysql://<username>:<password>@<host>/<dbname>[?<options>]

下面我们看一个例子:

#导入想关模块
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index
from sqlalchemy.orm import sessionmaker, relationship engine = create_engine("mysql+pymysql://root:123456@192.168.11.12:3306/haha", encoding='utf-8', max_overflow=5) # DBSession = sessionmaker(bind=engine)
#实例化
Base = declarative_base() # 主机表
class Host(Base): #声明类
__tablename__ = 'host' #需要创建的表名
nid = Column(Integer, primary_key=True, autoincrement=True)  #定义主键,自增1 ,其实这里还可以有其他参数
hostname = Column(String(32))
ip = Column(String(32), unique=True)
port = Column(String(32))
host_user = relationship('HostUser',secondary=lambda: HostToHostUser.__table__,backref='h')#映射表的外键 # 主机用户表
class HostUser(Base):
__tablename__ = 'host_user'
nid = Column(Integer, primary_key=True, autoincrement=True)
username = Column(String(32))
passwd = Column(String(32)) # 主机用户与主机关系表
class HostToHostUser(Base):
__tablename__ = 'host_to_hostuser'
nid = Column(Integer, primary_key=True, autoincrement=True)
user_nid = Column(Integer, ForeignKey('host_user.nid'))
host_nid = Column(Integer, ForeignKey('host.nid'))
host = relationship('Host', backref='h')
host_user = relationship('HostUser', backref='u') # 审计表
class AuditLog(Base):
__tablename__ = 'audit_log'
nid = Column(Integer, primary_key=True)
user_nid = Column(Integer, ForeignKey('host_user.nid'))
host_nid = Column(Integer, ForeignKey('host.nid'))
cmd = Column(String(255))
date = Column(String(255)) def init_db():
Base.metadata.create_all(engine) def drop_db():
Base.metadata.drop_all(engine) init_db() Session = sessionmaker(bind=engine)
session = Session()
#
# session.add_all((
Host(hostname='web1', ip='192.168.11.12', port='22', ),
Host(hostname='web2', ip='192.168.11.23', port='22', ),
Host(hostname='web3', ip='192.168.11.34', port='22', ),
Host(hostname='web4', ip='192.168.11.45', port='22', ),
Host(hostname='web5', ip='192.168.11.228', port='22', ),
))
session.commit() session.add_all([
HostUser(username='madking', passwd='123', ),
HostUser(username='oldboy', passwd='123', ),
])
session.commit() session.add_all((
HostToHostUser(user_nid='1', host_nid='1', ),
HostToHostUser(user_nid='1', host_nid='2', ),
HostToHostUser(user_nid='1', host_nid='5', ),
HostToHostUser(user_nid='2', host_nid='1', ),
))
session.commit()

sqlalchemy操作Mysql的更多相关文章

  1. 13、Flask实战第13天:SQLAlchemy操作MySQL数据库

    安装MySQL 在MySQL官网下载win版MySQL 双击运行 后面根据提示设置密码然后启动即可,这里我设置的密码是:123456 我们可以通过Navicat客户端工具连接上MySQL addres ...

  2. 【tips】ORM - SQLAlchemy操作MySQL数据库

    优先(官方文档SQLAlchemy-version1.2): sqlalchemy | 作者:斯芬克斯 推荐一(长篇幅version1.2.0b3):python约会之ORM-sqlalchemy | ...

  3. 【python】-- SQLAlchemy操作MySQL

    ORM.SQLAchemy orm英文全称object relational mapping,就是对象映射关系程序,简单来说就是类似python这种面向对象的程序来说一切皆对象,但是使用的数据库却都是 ...

  4. 通过sqlalchemy操作mysql

    # 安装 pip3 install sqlalchemy import sqlalchemy from sqlalchemy import create_enginefrom sqlalchemy.e ...

  5. Python 使用sqlalchemy操作MYSQL

    1. 安装sqlalchemy库 SQL操作引擎可能需要pymysql,故要安装如下两个程序 pip install sqlalchemy pip instal pymysql

  6. flask中使用SQLAlchemy操作mysql的一些注意事项和坑

    一 ImportError: cannot import name 'db' 由于app最后才加载,所以其他文件,比如models.py不能从app.py导入任何变量, 要使用db可以先定义一个,之后 ...

  7. python【第十二篇下】操作MySQL数据库以及ORM之 sqlalchemy

    内容一览: 1.Python操作MySQL数据库 2.ORM sqlalchemy学习 1.Python操作MySQL数据库 2. ORM sqlachemy 2.1 ORM简介 对象关系映射(英语: ...

  8. Python之路第十二天,高级(5)-Python操作Mysql,SqlAlchemy

    Mysql基础 一.安装 Windows: 1.下载 http://dev.mysql.com/get/Downloads/MySQL-5.6/mysql-5.6.31-winx64.zip 2.解压 ...

  9. flask 操作mysql的两种方式-sqlalchemy操作

    flask 操作mysql的两种方式-sqlalchemy操作 二.ORM sqlalchemy操作 #coding=utf-8 # model.py from app import db class ...

随机推荐

  1. DataTables自定义事件

    $(document).ready(function() { var eventFired = function(type) { var n = $('#demo_info')[0]; n.inner ...

  2. Kafka笔记--使用ubuntu为bocker(服务器)windows做producer和comsumer(客户端)

    原文连接:http://www.cnblogs.com/davidwang456/p/4201875.html 程序仍然使用之前的一篇博文中的例子 :http://www.cnblogs.com/gn ...

  3. JavaWeb学习笔记--filter开发

    介绍自定义的Filter类必须实现Filter接口,并且实现Filter接口定义的init() doFilter() destory()方法.其中init为初始化,destory为销毁 doFilte ...

  4. rtf表格的合并

    {\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fnil Calibri;}{\f1\fnil\fcharset134 \'cb\'ce\ ...

  5. ubuntu apt 命令参数(转)

    apt-get是一条linux命令,适用于deb包管理式的操作系统,主要用于自动从互联网的软件仓库中搜索.安装.升级.卸载软件或操作系统. apt-get update 在修改/etc/apt/sou ...

  6. gitosis使用笔记

    gitosis是Git下的权限管理工具,通过一个特殊的仓库(gitosis-admin.git)对Git权限进行管理. 1:服务端安装并配置gitosis (1)通过以下方式获取到安装包 root@w ...

  7. 关于javascript 回调函数

    http://segmentfault.com/q/1010000000212522 如何避免Javascript中回调函数的嵌套? http://javascript.ruanyifeng.com/ ...

  8. inux xsel 拷贝复制命令行输出放在系统剪贴板上

    转载自:http://oldratlee.com/post/2012-12-23/command-output-to-clip 为什么要这么做?直接把命令的输出(比如 grep/awk/sed/fin ...

  9. BZOJ1638: [Usaco2007 Mar]Cow Traffic 奶牛交通

    1638: [Usaco2007 Mar]Cow Traffic 奶牛交通 Time Limit: 5 Sec  Memory Limit: 64 MBSubmit: 571  Solved: 199 ...

  10. [转]ubuntu14.04安装好用的google拼音输入法

    原文网址:http://jingyan.baidu.com/article/219f4bf7d4a183de442d38f2.html 装了ubuntu14.04后感觉自带的拼音输入法不好用的有没有, ...