翼度科技»论坛 编程开发 python 查看内容

Python操作MySQL数据库的5种方式

5

主题

5

帖子

15

积分

新手上路

Rank: 1

积分
15
不管你是做数据分析,还是网络爬虫,Web 开发、亦或是机器学习,你都离不开要和数据库打交道,而 MySQL 又是最流行的一种数据库,这篇文章介绍 Python 操作 MySQL 的5种方式,你可以在实际开发过程中根据实际情况合理选择。
1、MySQLdb

MySQLdb又叫MySQL-python ,是 Python 连接 MySQL 最流行的一个驱动,很多框架都也是基于此库进行开发,遗憾的是它只支持 Python2.x,而且安装的时候有很多前置条件,因为它是基于C开发的库,在 Windows 平台安装非常不友好,经常出现失败的情况,现在基本不推荐使用,取代的是它的衍生版本。
  1. # 前置条件
  2. sudo apt-get install python-dev libmysqlclient-dev # Ubuntu
  3. sudo yum install python-devel mysql-devel # Red Hat / CentOS
  4. # 安装
  5. pip install MySQL-python
  6. Windows 直接通过下载 exe 文件安装
复制代码
  1. #!/usr/bin/python
  2. import MySQLdb
  3. db = MySQLdb.connect(
  4.      host="localhost",    # 主机名
  5.      user="root",         # 用户名
  6.      passwd="pythontab.com",  # 密码
  7.      db="testdb")        # 数据库名称
  8. # 查询前,必须先获取游标
  9. cur = db.cursor()
  10. # 执行的都是原生SQL语句
  11. cur.execute("SELECT * FROM mytable")
  12. for row in cur.fetchall():
  13.     print(row[0])
  14. db.close()
复制代码
2、mysqlclient

由于 MySQL-python(MySQLdb) 年久失修,后来出现了它的 Fork 版本 mysqlclient,完全兼容 MySQLdb,同时支持 Python3.x,是 Django ORM的依赖工具,如果你想使用原生 SQL 来操作数据库,那么推荐此驱动。安装方式和 MySQLdb 是一样的,Windows 可以在 https://www.lfd.uci.edu/~gohlke/pythonlibs/#mysqlclient 网站找到 对应版本的 whl 包下载安装。
  1. pip install mysqlclient
复制代码
3、PyMySQL

PyMySQL 是纯 Python 实现的驱动,速度上比不上 MySQLdb,最大的特点可能就是它的安装方式没那么繁琐,同时也兼容 MySQL-python
  1. pip install PyMySQL
  2. # 为了兼容mysqldb,只需要加入
  3. pymysql.install_as_MySQLdb()
复制代码
例子:
  1. import pymysql
  2. conn = pymysql.connect(host='127.0.0.1', user='root', passwd="pythontab.com", db='testdb')
  3. cur = conn.cursor()
  4. cur.execute("SELECT Host,User FROM user")
  5. for r in cur:
  6.     print(r)
  7. cur.close()
  8. conn.close()
复制代码
4、peewee

写原生 SQL 的过程非常繁琐,代码重复,没有面向对象思维,继而诞生了很多封装 wrapper 包和 ORM 框架,ORM 是 Python 对象与数据库关系表的一种映射关系,有了 ORM 你不再需要写 SQL 语句。提高了写代码的速度,同时兼容多种数据库系统,如sqlite, mysql、postgresql,付出的代价可能就是性能上的一些损失。如果你对 Django 自带的 ORM 熟悉的话,那么 peewee的学习成本几乎为零。它是 Python 中是最流行的 ORM 框架。
安装
  1. pip install peewee
复制代码
例子:
  1. import peewee
  2. from peewee import *
  3. db = MySQLDatabase('testdb', user='root', passwd='pythontab.com')
  4. class Book(peewee.Model):
  5.     author = peewee.CharField()
  6.     title = peewee.TextField()
  7.     class Meta:
  8.         database = db
  9. Book.create_table()
  10. book = Book(author="pythontab", title='pythontab is good website')
  11. book.save()
  12. for book in Book.filter(author="pythontab"):
  13.     print(book.title)
复制代码
官方文档:http://docs.peewee-orm.com/en/latest/peewee/installation.html
5、SQLAlchemy

如果想找一种既支持原生 SQL,又支持 ORM 的工具,那么 SQLAlchemy 是最好的选择,它非常接近 Java 中的 Hibernate 框架。
  1. #学习中遇到问题没人解答?小编创建了一个Python学习交流群:531509025
  2. from sqlalchemy import create_engine
  3. from sqlalchemy.orm import sessionmaker
  4. from sqlalchemy_declarative import Address, Base, Person
  5. class Address(Base):
  6.     __tablename__ = 'address'
  7.     id = Column(Integer, primary_key=True)
  8.     street_name = Column(String(250))
  9. engine = create_engine('sqlite:///sqlalchemy_example.db')
  10. Base.metadata.bind = engine
  11. DBSession = sessionmaker(bind=engine)
  12. session = DBSession()
  13. # Insert a Person in the person table
  14. new_person = Person(name='new person')
  15. session.add(new_person)
  16. session.commit()
复制代码
来源:https://www.cnblogs.com/python1111/p/18330889
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

举报 回复 使用道具