当前位置: 移动技术网 > IT编程>脚本编程>Python > Python 连接 MySQL 的几种方法

Python 连接 MySQL 的几种方法

2020年09月10日  | 移动技术网IT编程  | 我要评论
尽管很多 nosql 数据库近几年大放异彩,但是像 mysql 这样的关系型数据库依然是互联网的主流数据库之一,每个学 python 的都有必要学好一门数据库,不管你是做数据分析,还是网络爬虫,web

尽管很多 nosql 数据库近几年大放异彩,但是像 mysql 这样的关系型数据库依然是互联网的主流数据库之一,每个学 python 的都有必要学好一门数据库,不管你是做数据分析,还是网络爬虫,web 开发、亦或是机器学习,你都离不开要和数据库打交道,而 mysql 又是最流行的一种数据库,这篇文章介绍 python 操作 mysql 的几种方式,你可以在实际开发过程中根据实际情况合理选择。

1、mysql-python

mysql-python 又叫 mysqldb,是 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 文件安装

#!/usr/bin/python
import mysqldb

db = mysqldb.connect(
   host="localhost",  # 主机名
   user="john",     # 用户名
   passwd="megajonhy", # 密码
   db="jonhydb")    # 数据库名称

# 查询前,必须先获取游标
cur = db.cursor()

# 执行的都是原生sql语句
cur.execute("select * from your_table_name")

for row in cur.fetchall():
  print(row[0])

db.close()

2、mysqlclient

由于 mysql-python 年久失修,后来出现了它的 fork 版本 mysqlclient,完全兼容 mysqldb,同时支持 python3.x,是 django orm的依赖工具,如果你想使用原生 sql 来操作数据库,那么推荐此驱动。安装方式和 mysqldb 是一样的,windows 可以在 网站找到 对应版本的 whl 包下载安装。

# windows安装
pip install some-package.whl

# linux 前置条件
sudo apt-get install python3-dev # debian / ubuntu
sudo yum install python3-devel # red hat / centos
brew install mysql-connector-c # macos (homebrew)

pip install mysqlclient

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="xxx", db='mysql')
cur = conn.cursor()
cur.execute("select host,user from user")
for r in cur:
  print(r)
cur.close()
conn.close()

4、peewee

写原生 sql 的过程非常繁琐,代码重复,没有面向对象思维,继而诞生了很多封装 wrapper 包和 orm 框架,orm 是 python 对象与数据库关系表的一种映射关系,有了 orm 你不再需要写 sql 语句。提高了写代码的速度,同时兼容多种数据库系统,如sqlite, mysql、postgresql,付出的代价可能就是性能上的一些损失。如果你对 django 自带的 orm 熟悉的话,那么 peewee的学习成本几乎为零。它是 python 中是最流行的 orm 框架。

pip install peewee

一个例子

import peewee
from peewee import *

db = mysqldatabase('jonhydb', user='john', passwd='megajonhy')

class book(peewee.model):
  author = peewee.charfield()
  title = peewee.textfield()

  class meta:
    database = db

book.create_table()
book = book(author="me", title='peewee is cool')
book.save()
for book in book.filter(author="me"):
  print(book.title)

官方文档:

5、sqlalchemy

如果想找一种既支持原生 sql,又支持 orm 的工具,那么 sqlalchemy 是最好的选择,它非常接近 java 中的 hibernate 框架。

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

from sqlalchemy_declarative import address, base, person

class address(base):
  __tablename__ = 'address'
  id = column(integer, primary_key=true)
  street_name = column(string(250))

engine = create_engine('sqlite:///sqlalchemy_example.db')
base.metadata.bind = engine

dbsession = sessionmaker(bind=engine)
session = dbsession()

# insert a person in the person table
new_person = person(name='new person')
session.add(new_person)
session.commit()

现在差不多搞明白了这几种数据库驱动的优劣,接下来你就可以选择其中的一个进行系统的学习再把它应用到项目中去了,祝你学习开心,不懂的可以咨询我哈。

以上就是python 连接 mysql 的几种方法的详细内容,更多关于python 连接 mysql 的资料请关注移动技术网其它相关文章!

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网