首页 > 代码库 > python第十二天
python第十二天
python操作mysql
import pymysql
‘‘‘创建数据库连接‘‘‘
conn =pymysql.connect(host=‘localhost‘,port=3306,user=‘root‘,db=‘test‘);
‘‘‘创建游标‘‘‘
cursor =conn.cursor()
‘‘‘执行单条sql‘‘‘
effect_row = cursor.execute("insert into oldboydb (name,age,gender) value(‘tianshuai‘,‘20‘,‘M‘)")
‘‘‘执行多条sql‘‘‘
data =http://www.mamicode.com/{[‘alex‘,‘22‘,‘M‘],[‘jack‘,‘23‘,‘M‘]}
effect_row = cursor.executemany(‘insert into oldboydb (name,age,gender) values (%s,%s,%s)‘,data)
‘‘‘获取单条结果‘‘‘
print(conn.fetchone())
‘‘‘获取多条结果‘‘‘
print(conn.fetchmany(3))
‘‘‘获取所有结果‘‘‘
print(conn.fetchall())
‘‘‘提交数据‘‘‘
conn.commit()
‘‘‘关闭数据库连接‘‘‘
conn.close()
sqlachemy模块
创建表结构
from
sqlalchemy
import
create_engine
from
sqlalchemy.ext.declarative
import
declarative_base
from
sqlalchemy
import
Column, Integer, String
engine
=
create_engine(
"mysql+pymysql://root:alex3714@localhost/testdb?charset=utf8",
echo
=
True
)
Base = declarative_base() 定义表结构的不常用方式 book_m2m_author = Table(‘book_m2m_author‘, Base.metadata, Column(‘book_id‘,Integer,ForeignKey(‘books.id‘)), Column(‘author_id‘,Integer,ForeignKey(‘authors.id‘)), )
常用定义表结构的方式
Base
=
declarative_base()
#生成orm基类
class
User(Base):
__tablename__
=
‘user‘
#表名
id
=
Column(Integer, primary_key
=
True
)
name
=
Column(String(
32
))
password
=
Column(String(
64
))
Base.metadata.create_all(engine)
#创建表结构
插入数据
Session_class=
sessionmaker(bind
=
engine)
#创建与数据库的会话session class ,注意,这里返回给session的是个class,不是实例
Session
=
Session_class()
#生成session实例
user_obj
=
User(name
=
"alex"
,password
=
"alex3714"
)
#生成你要创建的数据对象
print
(user_obj.name,user_obj.
id
)
#此时还没创建对象呢,不信你打印一下id发现还是None
Session.add(user_obj)
#把要创建的数据对象添加到这个session里, 一会统一创建
print
(user_obj.name,user_obj.
id
)
#此时也依然还没创建
Session.commit()
#现此才统一提交,创建数据
查询
my_user
=
Session.query(User).filter_by(name
=
"alex"
).first() query()括号内指定查询的表名,filter_by()和filter()括号内指定查询条件,.first输出第一条数据;.all输出所有数据
def
__repr__(
self
): 在定义表结构的类中加上这个函数就可以让查询结果可视化,引号内的显示内容可以自定义
return
"<User(name=‘%s‘, password=‘%s‘)>"
%
(
self
.name,
self
.password)
objs
=
Session.query(User).
filter
(User.
id
>
0
).
filter
(User.
id
<
7
).
all
() 多条件查询
修改
my_user
=
Session.query(User).filter_by(name
=
"alex"
).first()
my_user.name
=
"Alex Li"
Session.commit()
回滚
Session.rollback()
统计
Session.query(User).
filter
(User.name.like(
"Ra%"
)).count()
分组
from
sqlalchemy
import
func
print
(Session.query(func.count(User.name),User.name).group_by(User.name).
all
() )
外键关联
from
sqlalchemy
import
ForeignKey
from
sqlalchemy.orm
import
relationship
class
Address(Base):
__tablename__
=
‘addresses‘
id
=
Column(Integer, primary_key
=
True
)
email_address
=
Column(String(
32
), nullable
=
False
)
user_id
=
Column(Integer, ForeignKey(
‘user.id‘
))
user
=
relationship(
"User"
, backref
=
"addresses"
)
#这个nb,允许你在user表里通过backref字段反向查出所有它在addresses表里的关联项
def
__repr__(
self
):
return
"<Address(email_address=‘%s‘)>"
%
self
.email_address
obj
=
Session.query(User).first()
for
i
in
obj.addresses:
#user表通过backref字段的addresses来查询Address表中关联的记录
print
(i)
addr_obj
=
Session.query(Address).first()
print
(addr_obj.user.name)
#在addr_obj里直接查关联的user表
多外键关联
即一个表中有多个字段关联了相同的另外一个表
from
sqlalchemy
import
Integer, ForeignKey, String, Column
from
sqlalchemy.ext.declarative
import
declarative_base
from
sqlalchemy.orm
import
relationship
Base
=
declarative_base()
class
Customer(Base):
__tablename__
=
‘customer‘
id
=
Column(Integer, primary_key
=
True
)
name
=
Column(String)
billing_address_id
=
Column(Integer, ForeignKey(
"address.id"
))
shipping_address_id
=
Column(Integer, ForeignKey(
"address.id"
))
billing_address
=
relationship(
"Address", foreign_keys
=
[billing_address_id]
)
shipping_address
=
relationship(
"Address", foreign_keys
=
[shipping_address_id]
)
class
Address(Base):
__tablename__
=
‘address‘
id
=
Column(Integer, primary_key
=
True
)
street
=
Column(String)
city
=
Column(String)
state
=
Column(String)
多对多关联
即两个表中每条记录都跟另一张表的多个记录关联
from sqlalchemy import Table, Column, Integer,String,DATE, ForeignKey from sqlalchemy.orm import relationship from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker Base = declarative_base() book_m2m_author = Table(‘book_m2m_author‘, Base.metadata, Column(‘book_id‘,Integer,ForeignKey(‘books.id‘)), Column(‘author_id‘,Integer,ForeignKey(‘authors.id‘)), ) class Book(Base): __tablename__ = ‘books‘ id = Column(Integer,primary_key=True) name = Column(String(64)) pub_date = Column(DATE) authors = relationship(‘Author‘,secondary=book_m2m_author,backref=‘books‘) def __repr__(self): return self.name class Author(Base): __tablename__ = ‘authors‘ id = Column(Integer, primary_key=True) name = Column(String(32)) def __repr__(self): return self.name
多对多删除记录
删除一本书的一个作者author_obj
=
s.query(Author).filter_by(name
=
"Jack"
).first()
book_obj
=
s.query(Book).filter_by(name
=
"跟Alex学把妹"
).first()
book_obj.authors.remove(author_obj)
#从一本书里删除一个作者
s.commit()
直接删除作者
author_obj
=
s.query(Author).filter_by(name
=
"Alex"
).first()
# print(author_obj.name , author_obj.books)
s.delete(author_obj)
s.commit()
设置数据库支持中文
eng = create_engine(‘mysql://root:root@localhost:3306/test2?charset=utf8‘,echo=True)
python第十二天
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。