python_day11のPython操
pyMysql
pymysql是python中操作Mysql的模块,其使用方法和Python2.7的MySQLdb几乎相同。
一、下载安装:
pip3 install pymysql
二、使用
1、执行SQL
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import pymysql
# 创建连接
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1')
# 创建游标
cursor = conn.cursor()
# 执行SQL,并返回收影响行数
effect_row = cursor.execute("update hosts set host = '1.1.1.2'")
# 执行SQL,并返回受影响行数
#effect_row = cursor.execute("update hosts set host = '1.1.1.2' where nid > %s", (1,))
# 执行SQL,并返回受影响行数
#effect_row = cursor.executemany("insert into hosts(host,color_id)values(%s,%s)", [("1.1.1.11",1),("1.1.1.11",2)])
# 提交,不然无法保存新建或者修改的数据
conn.commit()
# 关闭游标
cursor.close()
# 关闭连接
conn.close()
2、获取新创建数据自增ID
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import pymysql
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1')
cursor = conn.cursor()
cursor.executemany("insert into hosts(host,color_id)values(%s,%s)", [("1.1.1.11",1),("1.1.1.11",2)])
conn.commit()
cursor.close()
conn.close()
# 获取最新自增ID
new_id = cursor.lastrowid
3、获取查询数据
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import pymysql
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1')
cursor = conn.cursor()
cursor.execute("select * from hosts")
# 获取第一行数据
row_1 = cursor.fetchone()
# 获取前n行数据
# row_2 = cursor.fetchmany(3)
# 获取所有数据
# row_3 = cursor.fetchall()
conn.commit()
cursor.close()
conn.close()
注:在fetch数据时按照顺序进行,可以使用cursor.scroll(num,mode)来移动游标位置,如:
cursor.scroll(1,mode='relative') # 相对当前位置移动
cursor.scroll(2,mode='absolute') # 相对绝对位置移动
4、fetch数据类型
关于默认获取的数据是元祖类型,如果想要或者字典类型的数据,即:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import pymysql
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1')
# 游标设置为字典类型
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
r = cursor.execute("select * from tb1")
result = cursor.fetchone()
conn.commit()
cursor.close()
conn.close()
SQLAchemy
SQLAlchemy是Python编程语言下的一款ORM框架,该框架建立在数据库api之上,使用关系对象映射进行数据库操作,简言之便是:将对象转换成SQL,然后使用数据API执行SQL并获取执行结果。
SQLAlchemy本身无法操作数据库,其必须以来pymsql等第三方插件,Dialect用于和数据API进行交流,根据配置文件的不同调用不同的数据库API,从而实现对数据库的操作,如:
MySQL-Python
mysql+mysqldb://<user>:<passWord>@<host>[:<port>]/<dbname>
pymysql
mysql+pymysql://<username>:<password>@<host>/<dbname>[?<options>]
MySQL-Connector
mysql+mysqlconnector://<user>:<password>@<host>[:<port>]/<dbname>
cx_oracle
oracle+cx_oracle://user:pass@host:port/dbname[?key=value&key=value...]
更多详见:Http://docs.sqlalchemy.org/en/latest/dialects/index.html
一、底层处理
使用 Engine/ConnectionPooling/Dialect 进行数据库操作,Engine使用ConnectionPooling连接数据库,然后再通过Dialect执行SQL语句。
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from sqlalchemy import create_engine
engine = create_engine("mysql+pymysql://root:123@127.0.0.1:3306/t1", max_overflow=5)
# 执行SQL
# cur = engine.execute(
# "INSERT INTO hosts (host, color_id) VALUES ('1.1.1.22', 3)"
# )
# 新插入行自增ID
# cur.lastrowid
# 执行SQL
# cur = engine.execute(
# "INSERT INTO hosts (host, color_id) VALUES(%s, %s)",[('1.1.1.22', 3),('1.1.1.221', 3),]
# )
# 执行SQL
# cur = engine.execute(
# "INSERT INTO hosts (host, color_id) VALUES (%(host)s, %(color_id)s)",
# host='1.1.1.99', color_id=3
# )
# 执行SQL
# cur = engine.execute('select * from hosts')
# 获取第一行数据
# cur.fetchone()
# 获取第n行数据
# cur.fetchmany(3)
# 获取所有数据
# cur.fetchall()
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from sqlalchemy import create_engine
engine = create_engine("mysql+mysqldb://root:123@127.0.0.1:3306/s11", max_overflow=5)
# 事务操作
with engine.begin() as conn:
conn.execute("insert into table (x, y, z) values (1, 2, 3)")
conn.execute("my_special_procedure(5)")
conn = engine.connect()
# 事务操作
with conn.begin():
conn.execute("some statement", {'x':5, 'y':10})
注:查看数据库连接:show status like 'Threads%';
二、ORM功能使用
使用 ORM/Schema Type/SQL Expression Language/Engine/ConnectionPooling/Dialect 所有组件对数据进行操作。根据类创建对象,对象转换成SQL,执行SQL。
1、创建表
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy import create_engine
engine = create_engine("mysql+pymysql://root:123@127.0.0.1:3306/t1", max_overflow=5)
Base = declarative_base()
# 创建单表
class Users(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String(32))
extra = Column(String(16))
__table_args__ = (
UniqueConstraint('id', 'name', name='uix_id_name'),
Index('ix_id_name', 'name', 'extra'),
)
# 一对多
class Favor(Base):
__tablename__ = 'favor'
nid = Column(Integer, primary_key=True)
caption = Column(String(50), default='red', unique=True)
class Person(Base):
__tablename__ = 'person'
nid = Column(Integer, primary_key=True)
name = Column(String(32), index=True, nullable=True)
favor_id = Column(Integer, ForeignKey("favor.nid"))
# 多对多
class Group(Base):
__tablename__ = 'group'
id = Column(Integer, primary_key=True)
name = Column(String(64), unique=True, nullable=False)
port = Column(Integer, default=22)
class Server(Base):
__tablename__ = 'server'
id = Column(Integer, primary_key=True, autoincrement=True)
hostname = Column(String(64), unique=True, nullable=False)
# 定义在Server中的关系(就是利用第三张表将两张表联系起来,这里只需写这么一条即可)
# group = relationship('Group', secondary=ServerToGroup.__table__, backref='ggg')
class ServerToGroup(Base):
__tablename__ = 'servertogroup'
nid = Column(Integer, primary_key=True, autoincrement=True)
# 定义外键
server_id = Column(Integer, ForeignKey('server.id'))
group_id = Column(Integer, ForeignKey('group.id'))
# 定义关系(定义在关系表里面,也可以定义在其他表的类里,但写法有区别)
group = relationship('Group', backref='ggg')
server = relationship('Server', backref='sss')
def init_db():
Base.metadata.create_all(engine)
# 寻找Base的所有子类,按照子类的结构在数据库中生成对应的数据表信息
def drop_db():
Base.metadata.drop_all(engine)
2、操作表
# 创建表的基础之上
Session = sessionmaker(bind=engine)
session = Session()
增
删
改
查
其他
更多功能参见文档,猛击这里下载pdf |
表结构操作联系(看看就行)
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from sqlalchemy import create_engine,and_,or_,func,Table
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String,ForeignKey,UniqueConstraint,DateTime
from sqlalchemy.orm import sessionmaker,relationship
Base = declarative_base() #生成一个SqlORM 基类
# 服务器账号和组
# HostUser2Group = Table('hostuser_2_group',Base.metadata,
# Column('hostuser_id',ForeignKey('host_user.id'),primary_key=True),
# Column('group_id',ForeignKey('group.id'),primary_key=True),
# )
# 用户和组关系表,用户可以属于多个组,一个组可以有多个人
UserProfile2Group = Table('userprofile_2_group',Base.metadata,
Column('userprofile_id',ForeignKey('user_profile.id'),primary_key=True),
Column('group_id',ForeignKey('group.id'),primary_key=True),
)
# 程序登陆用户和服务器账户,一个人可以有多个服务器账号,一个服务器账号可以给多个人用
UserProfile2HostUser= Table('userprofile_2_hostuser',Base.metadata,
Column('userprofile_id',ForeignKey('user_profile.id'),primary_key=True),
Column('hostuser_id',ForeignKey('host_user.id'),primary_key=True),
)
class Host(Base):
__tablename__='host'
id = Column(Integer,primary_key=True,autoincrement=True)
hostname = Column(String(64),unique=True,nullable=False)
ip_addr = Column(String(128),unique=True,nullable=False)
port = Column(Integer,default=22)
def __repr__(self):
return "<id=%s,hostname=%s, ip_addr=%s>" %(self.id,
self.hostname,
self.ip_addr)
class HostUser(Base):
__tablename__ = 'host_user'
id = Column(Integer,primary_key=True)
AuthTypes = [
(u'ssh-passwd',u'SSH/Password'),
(u'ssh-key',u'SSH/KEY'),
]
# auth_type = Column(ChoiceType(AuthTypes))
auth_type = Column(String(64))
username = Column(String(64),unique=True,nullable=False)
password = Column(String(255))
host_id = Column(Integer,ForeignKey('host.id'))
# groups = relationship('Group',
# secondary=HostUser2Group,
# backref='host_list')
__table_args__ = (UniqueConstraint('host_id','username', name='_host_username_uc'),)
def __repr__(self):
return "<id=%s,name=%s>" %(self.id,self.username)
class Group(Base):
__tablename__ = 'group'
id = Column(Integer,primary_key=True)
name = Column(String(64),unique=True,nullable=False)
def __repr__(self):
return "<id=%s,name=%s>" %(self.id,self.name)
class UserProfile(Base):
__tablename__ = 'user_profile'
id = Column(Integer,primary_key=True)
username = Column(String(64),unique=True,nullable=False)
password = Column(String(255),nullable=False)
# host_list = relationship('HostUser',
# secondary=UserProfile2HostUser,
# backref='userprofiles')
# groups = relationship('Group',
# secondary=UserProfile2Group,
# backref='userprofiles')
def __repr__(self):
return "<id=%s,name=%s>" %(self.id,self.username)
class AuditLog(Base):
__tablename__ = 'audit_log'
id = Column(Integer,primary_key=True)
userprofile_id = Column(Integer,ForeignKey('user_profile.id'))
hostuser_id = Column(Integer,ForeignKey('host_user.id'))
action_choices2 = [
(u'cmd',u'CMD'),
(u'login',u'Login'),
(u'loGout',u'Logout'),
]
action_type = Column(ChoiceType(action_choices2))
#action_type = Column(String(64))
cmd = Column(String(255))
date = Column(DateTime)
# user_profile = relationship("UserProfile")
#bind_host = relationship("BindHost")
engine = create_engine("mysql+pymsql://root:123@localhost:3306/stupid_jumpserver",echo=False)
Base.metadata.create_all(engine) #创建所有表结构
相关文章