使用 Python 连接 MySQL 的方法
来源:互联网 发布:注册六西格玛黑带 知乎 编辑:程序博客网 时间:2024/05/22 12:04
MySQL-python 又叫 MySQLdb,是 Python 连接 MySQL 最流行的一个驱动,很多框架都也是基于此库进行开发,遗憾的是它只支持 Python2.x,而且安装的时候有很多前置条件,因为它是基于C开发的库,在 Windows 平台安装非常不友好,经常出现失败的情况,现在基本不推荐使用,取代的是它的衍生版本。
# 前置条件sudo apt-get install python-dev libmysqlclient-dev # Ubuntusudo yum install python-devel mysql-devel # Red Hat / CentOS# 安装pip install MySQL-python
#!/usr/bin/pythonimport MySQLdbdb = 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()
由于 MySQL-python 年久失修,后来出现了它的 Fork 版本 mysqlclient,完全兼容 MySQLdb,同时支持 Python3.x,是 Django ORM的依赖工具,如果你想使用原生 SQL 来操作数据库,那么推荐此驱动。安装方式和 MySQLdb 是一样的,Windows 可以在https://www.lfd.uci.edu/~gohlke/pythonlibs/#mysqlclient 网站找到对应版本的 whl 包下载安装。
# Windows安装pip install some-package.whl# linux 前置条件sudo apt-get install python3-dev # debian / Ubuntusudo yum install python3-devel # Red Hat / CentOSbrew install mysql-connector-c # macOS (Homebrew)pip install mysqlclient
PyMySQL 是纯 Python 实现的驱动,速度上比不上 PyMySQL,最大的特点可能就是它的安装方式没那么繁琐,同时也兼容 MySQL-python。
pip install PyMySQL# 为了兼容mysqldb,只需要加入pymysql.install_as_MySQLdb()
一个例子
import pymysqlconn = 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()
写原生 SQL 的过程非常繁琐,代码重复,没有面向对象思维,继而诞生了很多封装 wrapper 包和 ORM 框架,ORM 是 Python 对象与数据库关系表的一种映射关系,有了 ORM 你不再需要写 SQL 语句。提高了写代码的速度,同时兼容多种数据库系统,如sqlite, mysql、postgresql,付出的代价可能就是性能上的一些损失。如果你对 Django 自带的 ORM 熟悉的话,那么 peewee的学习成本几乎为零。它是 Python 中是最流行的 ORM 框架。
pip install peewee
一个例子
import peeweefrom peewee import *db = MySQLDatabase('jonhydb', user='john', passwd='megajonhy')class Book(peewee.Model): author = peewee.CharField() title = peewee.TextField() class Meta: database = dbBook.create_table()book = Book(author="me", title='Peewee is cool')book.save()for book in Book.filter(author="me"): print(book.title)
官方文档:http://docs.peewee-orm.com/en/latest/peewee/installation.html
如果想找一种既支持原生 SQL,又支持 ORM 的工具,那么 SQLAlchemy 是最好的选择,它非常接近 Java 中的 Hibernate 框架。
from sqlalchemy import create_enginefrom sqlalchemy.orm import sessionmakerfrom sqlalchemy_declarative import Address, Base, Personclass 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 = engineDBSession = sessionmaker(bind=engine)session = DBSession()# Insert a Person in the person tablenew_person = Person(name='new person')session.add(new_person)session.commit()
现在差不多搞明白了这几种数据库驱动的优劣,接下来你就可以选择其中的一个进行系统的学习再把它应用到项目中去了。
本文地址:http://www.linuxprobe.com/python-connect-mysql.html
- 使用 Python 连接 MySQL 的方法
- 使用 win10+python 2.7 连接 mysql 的方法
- MySQL 连接Python 的2 种方法
- 使用python连接mysql
- 使用Python连接MySQL
- python 3 连接mysql方法
- 使用Python连接MySQL数据库
- 使用Python连接MySQL数据库
- python连接MySQL、MongoDB、Redis、memcache等数据库的方法
- python连接MYSql数据库python连接MYSql数据库 使用 MySQLdb
- MySQL官方文档推荐的一个Python连接MySQL的方法—mysql.connector
- windows下python连接linux的mysql并且使用
- python连接mysql处理数据pymysql模块的使用
- python mysql使用连接池的通用操作类
- python获得mysql连接的最佳使用示例
- 使用datasource的方法建立到MySQL数据的连接。
- mysql的连接使用
- MySQL 连接的使用
- 兄弟连学python(3)——函数文档
- java.lang.IllegalArgumentException:A ServletContext is required to configure default servlet handlin
- 进程调度API之prepare_to_wait/prepare_to_wait_exclusive
- FIR滤波器和IIR滤波器的区别
- centos系统怎么修改线程
- 使用 Python 连接 MySQL 的方法
- GPIO概述
- HDU 2502 月之数【巧用位运算 + 快速幂】
- 171214---LAMP介绍之MySQL安装
- 0基础lua学习(二十)Lua单例
- nano pi 使用无线扩展板教程-无线模块的使用
- Linux基本操作
- Android 7.0 增加以太网设置DHCP和静态IP
- javascript中屏蔽esc键