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 ...
随机推荐
- 基于jeesite的cms系统(六):Lucene全文搜索引擎
1.lucene初始化 // @Value("${lucene.index.path}") private String indexPath = "/Users/vito ...
- 半导体制造、Fab以及Silicon Processing的基本知识
本文转载自微信公众号 - 手机技术资讯 , 链接 https://mp.weixin.qq.com/s/602xLKXcIw4ccTnhvDP1xw
- matlab 常用函数
Matlab常用函数 Matlab的内部常数 eps 浮点相对精度 pi 圆周率 exp 自然对数的底数e i 或j 虚数单位 Inf或 inf 无穷大 Matlab概率密度函数 ...
- go之路
目录 go初识[第一篇]初识 go初识[第二篇]包.变量.函数
- openwrt 编译
完整的编译过程: http://www.280i.com/tech/3353.html源更新: https://blog.csdn.net/ypbsyy/article/details/8121836 ...
- java平台学习笔记
java程序从编写源码开始到程序执行一共有三个阶段,编写期,编译期,运行期. 通常,人们都希望自己的程序更快(不仅仅是执行更快,也有编写更快),因此java在不断更新. java源码先通过javac编 ...
- 一、学习起步vue——安装
学习vue第一步:安装 (windows系统) 整个运行的命令: npm -v node -v 查看版本 npm uninstall -g vue-cli 卸载vue-cli npm install ...
- 实验1:C++简单程序设计(1)
实验目的 1. 掌握c++中类c部分的编程知识: 数据类型,常量,变量,运算符,表达式,分支结构,循环结构 2. 掌握C++中数据输入和输出的基本方法 3. 熟练使用c++程序开发环境,掌握c++程序 ...
- sortable.js 拖拽排序及配置项说明
// 拖动排序 $(function() { /*排序*/ //排序 // Simple list ]; new Sortable(list, { group: "name", a ...
- ad9361自测试校准
#include "config.h" #include "CONFIG_FPGA_ALL.h" #include "xparameters.h&qu ...