Python:连接mysql数据库的三种方式,mysql.connector, pymysql, MYSQLdb

一、关于PEP 249 

    PEP的全称是Python Enhancement Proposals,其中Enhancement是增强改进的意思,Proposals则可译为提案或建议书,所以合起来,比较常见的翻译是Python增强提案Python改进建议书。

 在数据库这方面python有PEP 249 -- Python Database API Specification v2.0,也就是关于数据库模块的规格说明书,所以在python当中,无论是mysql.connector还是pymysql,还是MYSQLdb,他们都遵循规格说明书,所以他们的API使用几乎是一样的,当然在规格说明书中列为可选项的,不同模块实现与否有差异。

二、三者的区别

    mysql-connector 是 MySQL 官方提供的驱动器, 它在Python中重新实现MySQL协议,它比较慢,但不需要C库,因此可移植性好。

    MySQLdb是一个围绕_mysql的瘦Python包装器,它使_mysql与Python DB API接口兼容(v2.0)。其中_mysql也是该作者开发的模块,它依赖C库,所以说MYSQLdb也是依赖C库的,因此它的可移植性不太好。但是由于是基于C库实现的,它的速度会快一些。一些开发者为了效率甚至直接使用_mysql模块。

    pymysql是由yutaka.matsubara开发维护的纯python实现的mysql模块。它相对于mysql.connector, MYSQLdb来说比较年轻。它的效率和可移植性和my-connector理论上是差不多的。

三、使用

1.连接

import mysql.connector
import MySQLdb
import pymysql

conn1 = mysql.connector.connect(host='localhost',
                                user='root',
                                passwd='yourpasswd',
                                db='db',
                                charset='utf8')

conn2 = MySQLdb.connect(host='localhost',
                        user='root',
                        passwd='yourpasswd',
                        db='db',
                        charset='utf8')

conn3 = pymysql.connect(host='localhost',
                        user='root',
                        passwd='yourpasswd',
                        db='db',
                        charset='utf8'
                        cursorclass=pymysql.cursors.DictCursor)

    pymysql可以支持查询结果为字典类型,只需要指定cursorclass是pymysql.cursors.DictCursor即可

2.增删查改

 由于他们的API是一样的,这里只使用一种

    (1)查询

conn = mysql.connector.connect(...)
cursor = conn.cursor()
sql1 = "select * from main limit 10"
cursor.execute(sql)
result1 = cursor.fetchall()   # 取出所有数据
result2 = cursor.fetchone()   # 取出第一条数据
result3 = cursor.fetchmany(5) # 取出结果中的五条数据
cursor.close()
conn.close()

  (2)增加, 删除,修改

conn = mysql.connector.connect(...)
cursor = conn.cursor()
sql1 = "insert into tablename values (%s, %s, %s)"
cursor.execute(sql1,(1,2,3))
cursor.executemany(sql1,[(1,2,3),(4,5,6)])
conn.commit()

sql2 = "delete from tablename where id=1000"
cursor.execute(sql2)
conn.commit()

sql3 = "update tablename set columnname = %s where id=%s"
cursor.execute(sql3, (0,1230))
cursor.executemany(sql, [(0,1030),(2,1230)])
conn.commit()

cursor.close()
conn.close()

   值得注意的是,所有对数据库数据有修改的操作,需要conn.commit()才会真正地生效。你可以几条语句一起提交,也可以单独提交。另外无论是数字,还是字符串,标识均使用%s。

   executemany支持插入批量数据。

四、参考资料

【1】https://www.cnblogs.com/abella/p/10056875.html

【2】https://pypi.org/project/PyMySQL/

【3】https://www.python.org/dev/peps/pep-0249/

【4】http://mysql-python.sourceforge.net/MySQLdb.html

原创文章 26 获赞 33 访问量 1868

猜你喜欢

转载自blog.csdn.net/qq_40765537/article/details/105876121