python-MYSQL(包括ORM)交互
1.首先,我们必须得连上我们的MYSQL数据库。个人遇到连不上MYSQL数据的问题主要有:数据库的权限问题、数据库表权限的问题
同时获取数据库中的数据等。
//==========================================================================
数据库连不上:
授权:
grant all on *.* to 'root'@'youruser' identified by 'yourpassword';
flush privileges;
//==========================================================================
//==========================================================================
//连接数据库
//==========================================================================
import pymysql
# 创建连接 相当于创建了一个socket
conn = pymysql.connect(host='localhost', port=3306, user='LOCALHOST',password='',db='lll')
# 创建游标
cursor = conn.cursor() # 执行SQL,并返回收影响行数
effect_row = cursor.execute("select * from student") print(effect_row)
print(cursor.fetchone())
print(cursor.fetchone())#获取一条数据
print('====================================')
print(cursor.fetchall())#获取前面没有获取到的所有数据 相当于和读文件一样
2.插入数据
import pymysql
# 创建连接 相当于创建了一个socket
conn = pymysql.connect(host='localhost', port=3306, user='LOCALHOST',password='',db='lll')
# 创建游标
cursor = conn.cursor()
data = [
("N1","","2018-5-25"),
("N2","","2018-5-25"),
("N3","","2018-5-25")
]
cursor.executemany("insert into student(name,age,register_date)values(%s,%s,%s)", data)
# 提交,不然无法保存新建或者修改的数据
conn.commit() #默认开启事务的 需要提交
//==========================================================================
3.查询数据
//==========================================================================
#查询数据
import pymysql
# 创建连接 相当于创建了一个socket
conn = pymysql.connect(host='localhost', port=3306, user='LOCALHOST',password='',db='lll')
# 创建游标
cursor = conn.cursor()
# 获取第一行数据
row_1 = cursor.fetchone()
# 获取前n行数据
# row_2 = cursor.fetchmany(3)
# 获取所有数据
# row_3 = cursor.fetchall()
conn.commit()
cursor.close()
conn.close()
//==========================================================================
4.SQLAchemy
orm英文全称object relational mapping,就是对象映射关系程序,简单来说我们类似python这种面向对象的程序来说一切皆对象,但是我们使用的数据库却都是关系型的,为了保证一致的使用习惯,通过orm将编程语言的对象模型和数据库的关系模型建立映射关系,这样我们在使用编程语言对数据库进行操作的时候可以直接使用编程语言的对象模型进行操作就可以了,而不用直接使用sql语言。
在Python中,最有名的ORM框架是SQLAlchemy。用户包括openstack\Dropbox等知名公司或应用,主要用户列表
创建表:
//==========================================================================
//SQLAchemy
//==========================================================================
import sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String engine = create_engine("mysql+pymysql://LOCALHOST:123456@localhost/lll",
encoding='utf-8', echo=True)#如果不echo = true 就不打印 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) #创建表结构
#===========================================================================
//另一种创建方法不常用的
#===========================================================================
#===========================================================================
//另一种创建方法不常用的
#===========================================================================
from sqlalchemy import Table, MetaData, Column, Integer, String, ForeignKey
from sqlalchemy.orm import mapper
metadata = MetaData() # 创建一个表
user = Table('user', metadata,
Column('id', Integer, primary_key=True),
Column('name', String(50)),
Column('fullname', String(50)),
Column('password', String(12))
)
# 一般不用
class User(object):
def __init__(self, name, fullname, password):
self.name = name
self.fullname = fullname
self.password = password mapper(User, user)
#the table metadata is created separately with the Table construct,
#then associated with the User class via the mapper() function
#===========================================================================
#===========================================================================
#最基本的表我们创建好了,那我们开始用orm创建一条数据试试
#===========================================================================
#===========================================================================
#最基本的表我们创建好了,那我们开始用orm创建一条数据试试
#===========================================================================
from sqlalchemy.orm import sessionmaker
# 最基本的表我们创建好了,那我们开始用orm创建一条数据试试
Session_class = sessionmaker(bind = engine) #创建与数据库的会话session class ,注意,这里返回给session的是个class,不是实例
Session = Session_class() #生成session实例 user_obj = User(name="NEOKARL",password="NEOKarl") #生成你要创建的数据对象
user_obj2 = User(name="NEOKARL2",password="NEOKarl2") #生成你要创建的数据对象
print(user_obj.name,user_obj.id) #此时还没创建对象呢,不信你打印一下id发现还是None Session.add(user_obj) #把要创建的数据对象添加到这个session里, 一会统一创建
Session.add(user_obj2) #把要创建的数据对象添加到这个session里, 一会统一创建
print(user_obj.name,user_obj.id) #此时也依然还没创建 Session.commit() #现此才统一提交,创建数据
# =========================================================================
# 查询数据
# =========================================================================
在查询之前修改部分代码:
#===========================================================================
#查询数据
#===========================================================================
class User(Base):
__tablename__ = 'user' #表名
id = Column(Integer, primary_key=True)
name = Column(String(32))
password = Column(String(64)) def __repr__(self):
return "<%s name :%s>" %(self.id,self.name)
# =========================================================================
# 查询所有的数据
# =========================================================================
data = Session.query(User).filter_by().all()
print(data)
#查询数据
data = Session.query(User).filter_by(name="NEOKARL").all()
print(data[0].name,data[0].password)
#查询id>2的所有数据
data = Session.query(User).filter(User.id >2).all()
print(data[0].name,data[0].password) #查询id=2的所有数据
data = Session.query(User).filter_by(id = 2).all()
print(data[0].name,data[0].password) data = Session.query(User).filter(User.id==2).all()
print(data[0].name,data[0].password) #多条件查询:
data = Session.query(User).filter(User.id>2).filter(User.id<5).all()
print(data[0].name,data[0].password)
# =========================================================================
# 修改
# =========================================================================
my_user = Session.query(User).filter_by(name="NEOKARL").first()
my_user.name = "PerfectWanan"
Session.commit()
00
# =========================================================================
# 回滚
# ========================================================================= fake_user = User(name='Rain', password='')
Session.add(fake_user) print(Session.query(User).filter(User.name.in_(['Jack','rain'])).all() ) #这时看session里有你刚添加和修改的数据 Session.rollback() #此时你rollback一下 print(Session.query(User).filter(User.name.in_(['Jack','rain'])).all() ) #再查就发现刚才添加的数据没有了。 # =========================================================================
# 分组统计
# =========================================================================
print(Session.query(User).filter(User.name.in_(['Jack','rain'])).count())
# from sqlalchemy import func
# print(Session.query(func.count(User.name),User.name).group_by(User.name).all() )
# =========================================================================
# 链表
# =========================================================================
s1 = Student(name = "",age = "",register_date = "2018-5-25")
Session.add(s1)
Session.commit()
# =========================================================================
# join连表查询
# =========================================================================
print(Session.query(User,Student).filter(User.id == Student.stu_id).all())
# 需要有外部关联才能查询
# print(Session.query(User).join(Student).all())
外键关联:
import sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String
# 需要导入其他的模块
from sqlalchemy.orm import sessionmaker
# 我们创建一个表,跟student表关联
from sqlalchemy import ForeignKey
from sqlalchemy.orm import relationship
# 创建一个表
# 如果已经创建了就不再需要创建了
engine = create_engine("mysql+pymysql://LOCALHOST:123456@localhost/lll",
encoding='utf-8')#如果不echo = true 就不打印 Base = declarative_base() #生成orm基类 class Student(Base):
__tablename__ = 'student'
stu_id = Column(Integer, primary_key=True)
name = Column(String(32), nullable=False)
age = Column(String(32), nullable=False)
register_date = Column(String(32), nullable=False) # user = relationship("User", backref="addresses") #这个nb,允许你在user表里通过backref字段反向查出所有它在addresses表里的关联项 def __repr__(self):
return "<%s name :%s>" %(self.stu_id,self.name) class StudyRecord(Base):
__tablename__ = 'study_record'
id = Column(Integer, primary_key=True)
day = Column(Integer,nullable=False)
status = Column(String(32),nullable=False) #===========================================================
student = relationship("Student", backref="my_study_record") #student = query(Student).filter(Student.id == stu_obj.stu_id).first()
#===========================================================
#外键关联
stu_id = Column(Integer,ForeignKey("student.stu_id")) def __repr__(self):
return "<%s day :%s status:%s>" %(self.student.name,self.day,self.status) Base.metadata.create_all(engine) #创建表结构 # 最基本的表我们创建好了,那我们开始用orm创建一条数据试试
Session_class = sessionmaker(bind = engine) #创建与数据库的会话session class ,注意,这里返回给session的是个class,不是实例
Session = Session_class() #生成session实例 # s1 = Student(name = "jack",age = "5551",register_date = "2018-5-25")
# s2 = Student(name = "neo",age = "5552",register_date = "2018-5-26")
# s3 = Student(name = "karl",age = "5553",register_date = "2018-5-27")
# s4 = Student(name = "perfectwanan",age = "5554",register_date = "2018-5-28") # study_obj1 = StudyRecord(day = 1,status = "YES",stu_id = 3)
# study_obj2 = StudyRecord(day = 2,status = "NO",stu_id = 3)
# study_obj3 = StudyRecord(day = 3,status = "YES",stu_id = 3)
# study_obj4 = StudyRecord(day = 3,status = "YES",stu_id = 4) # Session.add_all([s1,s2,s3,s4,study_obj1,study_obj2,study_obj3,study_obj4]) study_obj = Session.query(Student).filter(Student.name == "neo").first()
print(study_obj.my_study_record) Session.commit()
#===========================================================================
#结果:[<neo day :1 status:YES>, <neo day :2 status:NO>, <neo day :3 status:YES>]
#===========================================================================
需要注意的是:
我的数据表为:
#===========================================================================
#sqlalchemy 多外键关联
#===========================================================================
orm_many_fk.py
import sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String
# 需要导入其他的模块
from sqlalchemy.orm import sessionmaker
# 我们创建一个表,跟student表关联
from sqlalchemy import ForeignKey
from sqlalchemy.orm import relationship
engine = create_engine("mysql+pymysql://LOCALHOST:123456@localhost/lll",
encoding='utf-8',echo = True)#如果不echo = true 就不打印
Base = declarative_base() class Customer(Base):
__tablename__ = 'customer'
id = Column(Integer, primary_key=True)
name = Column(String(64)) 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(64))
city = Column(String(64))
state = Column(String(64))
Base.metadata.create_all(engine) #创建表结构
orm_api.py
import orm_many_fk
# 需要导入其他的模块
from sqlalchemy.orm import sessionmaker
# 最基本的表我们创建好了,那我们开始用orm创建一条数据试试
Session_class = sessionmaker(bind = orm_many_fk.engine) #创建与数据库的会话session class ,注意,这里返回给session的是个class,不是实例
Session = Session_class() #生成session实例 addr1 = orm_many_fk.Address(street = "Tiantongyuan",city = "Changping",state = "BJ")
addr2 = orm_many_fk.Address(street = "Wudaokou",city = "Haidian",state = "BJ")
addr3 = orm_many_fk.Address(street = "Yanjiao",city = "Langfang",state = "HB") Session.add_all([addr1,addr2,addr3]) c1 = orm_many_fk.Customer(name = "wanan",billing_address= addr1,shipping_address = addr2)
c2 = orm_many_fk.Customer(name = "jcak",billing_address= addr3,shipping_address = addr2) Session.add_all([c1,c2])
#===========================================================================
#如果出现以下问题提示
#===========================================================================
sqlalchemy.exc.AmbiguousForeignKeysError: Could
not
determine join
condition between parent
/
child tables on relationship
Customer.billing_address
-
there are multiple foreign key
paths linking the tables. Specify the
'foreign_keys'
argument,
providing a
list
of those columns which should be
counted as containing a foreign key reference to the parent table.
#===========================================================================
class Customer(Base):
__tablename__ = 'customer'
id = Column(Integer, primary_key=True)
name = Column(String(64)) 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])
这样sqlachemy就能分清哪个外键是对应哪个字段了
#===========================================================================
#sqlalchemy 多对多外键关联
#===========================================================================
#一本书可以有多个作者,一个作者又可以出版多本书
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
# 创建一个表
# 如果已经创建了就不再需要创建了
engine = create_engine("mysql+pymysql://LOCALHOST:123456@localhost/lll",
encoding='utf-8')#如果不echo = true 就不打印
import orm_mtom
from sqlalchemy.orm import sessionmaker
# 最基本的表我们创建好了,那我们开始用orm创建一条数据试试
Session_class = sessionmaker(bind = orm_mtom.engine) #创建与数据库的会话session class ,注意,这里返回给session的是个class,不是实例
s = Session_class() #生成session实例 # b1 = Book(name="跟0学Python")
# b2 = Book(name="跟0学把妹")
# b3 = Book(name="跟0学装逼")
# b4 = Book(name="跟0学开车") # a1 = Author(name="Alex")
# a2 = Author(name="Jack")
# a3 = Author(name="Rain") # b1.authors = [a1,a2]
# b2.authors = [a1,a2,a3] # s.add_all([b1,b2,b3,b4,a1,a2,a3]) print('--------通过书表查关联的作者---------') book_obj = s.query(Book).filter_by(name="跟0学Python").first()
print(book_obj.name, book_obj.authors)
print('--------通过作者表查关联的书---------')
author_obj =s.query(Author).filter_by(name="").first()
print(author_obj.name , author_obj.books) s.commit()
python-MYSQL(包括ORM)交互的更多相关文章
- python 之路,Day11(上) - python mysql and ORM
python 之路,Day11 - python mysql and ORM 本节内容 数据库介绍 mysql 数据库安装使用 mysql管理 mysql 数据类型 常用mysql命令 创建数据库 ...
- Python-Day12 Python mysql and ORM
一.Mysql数据库 1.什么是数据库? 数据库(Database)是按照数据结构来组织.存储和管理数据的仓库, 每个数据库都有一个或多个不同的API用于创建,访问,管理,搜索和复制所保存的数据 ...
- python mysql and ORM
http://www.cnblogs.com/alex3714/articles/5950372.html 9. ORM sqlachemy学习 http://www.cnblogs.com/alex ...
- Day11 - Mysql and ORM
python 之路,Day11 - python mysql and ORM 本节内容 数据库介绍 mysql 数据库安装使用 mysql管理 mysql 数据类型 常用mysql命令 创建数据库 ...
- python下的orm基本操作(1)--Mysql下的CRUD简单操作(含源码DEMO)
最近逐渐打算将工作的环境转移到ubuntu下,突然发现对于我来说,这ubuntu对于我这种上上网,收收邮件,写写博客,写写程序的时实在是太合适了,除了刚接触的时候会不怎么完全适应命令行及各种权限管理, ...
- Python MySQL ORM QuickORM hacking
# coding: utf-8 # # Python MySQL ORM QuickORM hacking # 说明: # 以前仅仅是知道有ORM的存在,但是对ORM这个东西内部工作原理不是很清楚, ...
- python操作三大主流数据库(3)python操作mysql③python操作mysql的orm工具sqlaichemy安装配置和使用
python操作mysql③python操作mysql的orm工具sqlaichemy安装配置和使用 手册地址: http://docs.sqlalchemy.org/en/rel_1_1/orm/i ...
- 第一节、Alex 讲解 python+mysql 交互;
Python Mysql 交互 A.Alex 的语法展示: import MySQLdb try: conn=MySQL.connect(host='localhost',user='ro ...
- python mysql orm
Python中操作mysql的pymysql模块详解:https://www.cnblogs.com/wt11/p/6141225.html Python 12 - Mysql & ORM:h ...
- 第二百八十九节,MySQL数据库-ORM之sqlalchemy模块操作数据库
MySQL数据库-ORM之sqlalchemy模块操作数据库 sqlalchemy第三方模块 sqlalchemysqlalchemy是Python编程语言下的一款ORM框架,该框架建立在数据库API ...
随机推荐
- Redux中间件组合方法
中间件 https://redux.js.org/glossary#middleware 中间件在发送端 action端点 和 处理方reducer的端点之间. 主要负责将async action转换 ...
- Keras的一些功能函数
摘自: https://www.cnblogs.com/Anita9002/p/8136357.html 1.模型的信息提取 # 节点信息提取 config = model.get_config() ...
- java项目部署常用linux命令
1.显示当前所有java进程pid的命令:jps2.查找文件或文件夹目录查找目录:find /(查找范围) -name '查找关键字' -type d查找文件:find /(查找范围) -name 查 ...
- selenium定位方式-Xpath使用方法
什么是Xpath? XPath是XML的路径语言,通俗一点讲就是通过元素的路径来查找到这个标签元素. 一. 在火狐浏览器上安装Xpath 方法如下: 1.使用 Firefox 访问 https://a ...
- axios formData提交数据 && axios设置charset无效???
但是这样会出现一个问题,什么问题呢? 我设置了请求头编码utf-8,但是没生效 content-type里面没有出现utf-8???????查了很多资料,说这是axios固有的bug,我....... ...
- 2018-2019-2 20165231 王杨鸿永 Exp6 信息搜集与漏洞扫描
实践目标 掌握信息搜集的最基础技能与常用工具的使用方法. 2.实践内容 (1)各种搜索技巧的应用 (2)DNS IP注册信息的查询 (3)基本的扫描技术:主机发现.端口扫描.OS及服务版本探测.具体服 ...
- 【转】Oracle之索引
简介 1.说明 1)索引是数据库对象之一,用于加快数据的检索,类似于书籍的目录.在数据库中索引可以减少数据库程序查询结果时需要读取的数据量,类似于在书籍中我们利用目录可以不用翻阅整本书即可找到想要的信 ...
- 020_Linux的孤儿进程与僵尸进程(Unix系统编程)
1.前言 之前在看<unix环境高级编程>第八章进程时候,提到孤儿进程和僵尸进程,一直对这两个概念比较模糊.今天被人问到什么是孤儿进程和僵尸进程,会带来什么问题,怎么解决,我只停留在概念上 ...
- C# 根据出生日期(年月日)计算年龄的代码
public int GetAgeByBirthdate(DateTime birthdate) { DateTime now = DateTime.Now; int age = now.Year - ...
- java http post/get 服务端和客户端实现json传输
注:本文来源于<java http post/get 服务端和客户端实现json传输> 最近需要写http post接口所以学习下. 总的还是不难直接上源码! PostHttpClient ...