虽然近年来很多NoSQL数据库大放异彩,但是像MySQL这样的关系型数据库仍然是互联网上的主流数据库之一。每个学习Python的人都必须学习一个数据库,无论是做数据分析、网络爬虫、网页开发还是机器学习,都离不开数据库,而MySQL是最流行的数据库。本文介绍了Python操作MySQL的几种方式,大家在实际开发过程中可以根据实际情况合理选择。1、MySQL-pythonMySQL-python,也叫MySQLdb,是Python连接MySQL***的驱动。许多框架也是基于这个库开发的。遗憾的是,它只支持Python2.x,而且预装条件很多,因为是基于C开发的库,在Windows平台上安装很不友好,经常会失败。现在基本不推荐使用,其衍生版本被替换。#前提sudoapt-getinstallpython-devlibmysqlclient-dev#Ubuntusudoyuminstallpython-develmysql-devel#RedHat/CentOS#安装pipinstallMySQL-pythonWindows直接下载exe文件安装,公众号回复“win”获取下载链接#!/usr/bin/pythonimportMySQLdbdb=MySQLdb.connect(host="localhost",#hostnameuser="john",#usernamepasswd="megajonhy",#passworddb="jonhydb")#databasename#查询之前,必须先获取游标cur=db.cursor()#ExecutenativeSQLstatementscur.execute("SELECT*FROMYOUR_TABLE_NAME")forrowincur.fetchall():print(row[0])db.close()2、mysqlclient由于MySQL-python年年久失修,后来出现了它的Fork版本mysqlclient。完全兼容MySQLdb,支持Python3.x。它是DjangoORM的依赖工具。如果你想使用原生的SQL来操作数据库,那么推荐这个驱动。安装方法同MySQLdb。Windows可以在https://www.lfd.uci.edu/~gohlke/pythonlibs/#mysqlclient网站下载安装对应版本的whl包。#Windows安装pipinstallsome-package.whl#linuxpreconditionssudoapt-getinstallpython3-dev#debian/Ubuntusudoyuminstallpython3-devel#RedHat/CentOSbrewinstallmysql-connector-c#macOS(Homebrew)pipinstallmysqlclient3,PyMySQLPyMySQL是纯Python驱动,比NotonMySQLdb更快,最大的特点可能是它的安装方法没有那么繁琐,而且还兼容MySQL-pythonpipinstallPyMySQL#为了兼容mysqldb,只需要添加一个pymysql.install_as_MySQLdb()的例子importpymysqlconn=pymysql.connect(host='127.0.0.1',user='root',passwd="xxx",db='mysql')cur=conn.cursor()cur.execute("SELECTHost,UserFROMuser")forrincur:print(r)cur.close()conn.close()4、peewee写原生SQL的过程非常繁琐,代码重复,没有面向对象的思想。然后诞生了很多打包wrapper包和ORM框架。ORM是Python对象与数据库关系表之间的映射关系。使用ORM,您不再需要编写SQL语句。提高了编写代码的速度,兼容各种数据库系统,如sqlite、mysql、postgresql等。付出的代价可能是性能上的一些损失。如果熟悉Django自带的ORM,那么peewee的学习成本几乎为零。它是Python中最流行的ORM框架。pipinstallpeewee一个例子dbBook.create_table()book=Book(author="me",title='Peeweeiscool')book.save()forbookinBook.filter(author="me"):print(book.title)官方文档:http://docs.peewee-orm.com/en/latest/peewee/installation.html5.SQLAlchemy如果你想找一个同时支持原生SQL和ORM的工具,那么SQLAlchemy是最好的选择,它在Hibernate中非常接近Java框架。fromsqlalchemyimportcreate_enginefromsqlalchemy.ormimportsessionmakerfromsqlalchemy_declarativeimportAddress,Base,PersonclassAddress(Base):__tablename__='address'id=Column(Integer,primary_key=True)street_name=Column(String(250))engine=create_engine('sqlite:///sqlalchemydb')_example。base.metadata.bind=engineDBSession=sessionmaker(bind=engine)session=DBSession()#InsertaPersoninthepersontablenew_person=Person(name='new_person')session.add(new_person)session.commit()现在我差不多明白这几种数据库了驱动程序的优点和缺点,那么你可以选择其中的一个进行系统学习,然后将其应用到项目中。祝你学习愉快。不明白的可以咨询我。
