1、MySQLdb
MySQLdb又叫MySQL-python ,是 Python 连接 MySQL 最流行的一个驱动,很多框架都也是基于此库进行开发,遗憾的是它只支持 Python2.x,而且安装的时候有很多前置条件,因为它是基于C开发的库,在 Windows 平台安装非常不友好,经常出现失败的情况,现在基本不推荐使用,取代的是它的衍生版本。
# 前置条件 sudo apt-get install python-dev libmysqlclient-dev # Ubuntu sudo yum install python-devel mysql-devel # Red Hat / CentOS # 安装 pip install MySQL-python Windows 直接通过下载 exe 文件安装 import MySQLdb db = MySQLdb.connect( host="localhost", # 主机名 user="root", # 用户名 passwd="pythontab.com", # 密码 db="testdb") # 数据库名称 # 查询前,必须先获取游标 cur = db.cursor() # 执行的都是原生SQL语句 cur.execute("SELECT * FROM mytable") for row in cur.fetchall(): print(row[0]) 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 包下载安装。
pip install mysqlclient
虽然用pip安装的时候是mysqlclient,但是在python中使用的时候,仍然是用
import MySQLdb
import MySQLdb#使用同pymysql差不多
# 注意 这里需要额外导入, 不然会报module 'MySQLdb' has no attribute 'cursors'的错误
import MySQLdb.cursors as cors
# 打开数据库连接
db = MySQLdb.connect("localhost", "testuser", "test123", "TESTDB", charset='utf8',
cursorclass=cors.DictCursor)
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# SQL 插入语句
sql="insert into EMPLOYEE values(%s,%s,%s,%s)"
try:
# 执行sql语句
cursor.executemany(sql,[('Smith','Tom',15,'M',1500),('Mac', 'Mohan', 20, 'M', 2000)])
# 提交到数据库执行
db.commit()
except:
# Rollback in case there is any error
db.rollback()
# 关闭数据库连接
db.close()
3、PyMySQL
PyMySQL 是纯 Python 实现的驱动,速度上比不上 MySQLdb,最大的特点可能就是它的安装方式没那么繁琐,同时也兼容 MySQL-python
pip install PyMySQL
# 为了兼容mysqldb,只需要加入
pymysql.install_as_MySQLdb()
例子:
import pymysql
conn = pymysql.connect(host='127.0.0.1', user='root', passwd="pythontab.com", db='testdb')
cur = conn.cursor()
cur.execute("SELECT Host,User FROM user")
for r in cur:
print(r)
cur.close()
conn.close()
重点讲解pymysql,用的最广
import pymysql #python连接数据库 con = pymysql.connect( host = '127.0.0.1',#本机服务地址 port = 3306,#端口 user = 'root',#数据库用户 password = 'root',#数据库密码 database='runoob', # 库名称,也可以简写为db charset='utf8' # 字符编码 #autocommit=True # 涉及到增删改 自动二次确认 ) #定义一个游标,通过游标来操作数据库,所有的操作都需要通过游标来操作 cur = con.cursor()#括号内不写参数,数据是元组套元组 # cur = conn_obj.cursor( # cur=pymysql.cursors.DictCursor # ) # 括号内写参数,数据会处理成字典形式 #通过cur.execute()来执行sql语句 tables = cur.execute('show tables')#查询表数量 # print(tables)#23 all = cur.fetchall()#获取所有表名,这里获取的内容跟上个查询语句相关 one = cur.fetchone()#获取第一个表 # print(all) #建表 #创建一个变量用来接收sql语句,三引号便于编辑sql语句 table = ''' create table zj001( name VARCHAR(10), age VARCHAR(10) ) ''' # cur.execute(table) ''' 数据的增删改查四个操作是有分级的 查 不会改变真正的数据,权限要求最低 增、改、删 都会影响真正的数据,权限要求较高 pymysql针对增、改、删三个操作设置了二次确认,如果不确认则不会真正修改数据库 可以在连接配置里面添加 autocommit=True # 涉及到增删改 自动二次确认 ''' #插入数据,需要commit sql = ''' insert into zj001(name,age) values('张三','18') ''' # cur.execute(sql) # con.commit() #插入多条 # cur.executemany("insert into zj001(name,age) values(%s,%s)",[('李四','19'),('王五','20')]) # con.commit() #查询数据,需要连续查询 # select = cur.execute('select * from zj001') # all = cur.fetchall()#这里获取的内容跟上个查询语句相关 # print(select)#行数 # print(all) #删除数据 # delete = cur.execute("delete from zj001 where name='张三'") # con.commit() # select = cur.execute('select * from zj001') # all = cur.fetchall() # print(all) #修改数据 # update = cur.execute("update zj001 set age='100' where name='李四'") # con.commit() # select = cur.execute('select * from zj001') # all = cur.fetchall() # print(all) # res = cur.fetchmany(2) # 获取指定个数数据 # cur.scroll(2, 'absolute') # 相对于起始位置往后移动一个单位 # # cur.scroll(0, 'relative') # 相对于当前位置往后移动一个单位 # res = cur.fetchall() # 获取所有数据 # print(res) #其他dml,ddl语句......,可以将这些操作封装到一个类里面