Python连接MySQL的几种方式

目前,常见的Python连接MySQL主要有以下几种方式:SQLAlchemy,PyMySQL,peewee,MySQLdb(只支持Python2.x,已基本废弃)MySQLclient等,下面我们分别做相应介绍。

1、PyMySQL
安装方式简单,同时也兼容 MySQL-python,功能强大,它的运行原理如下图所示:


image.png

实现代码:

import pymysql

pip install PyMySQL

# 为了兼容mysqldb,只需要加入

pymysql.install_as_MySQLdb()

# 打开数据库连接

conn = pymysql.connect(host='*.*.*.*',

                       port=3306,

                       user='*',

                       passwd='*',

                       charset = 'utf8'

                       )

# 使用 cursor() 方法创建一个游标对象 cursor                       

cursor = conn.cursor()

# 使用 execute()  方法执行 SQL 查询

cursor.execute("show databases;")

cursor.execute("use database_name;")

cursor.execute("show tables;")

cursor.execute("select * from tables_name")

# 使用 fetchone() 方法获取单条数据;使用 fetchall() 方法获取所有数据

data = cursor.fetchall()

for item in data:

    print(item[0])

# 关闭数据库连接

cursor.close()

2、SQLAlchemy
sqlalchemy是python的orm程序,(object relational mapping,对象映射关系程序)在使用sqlalchemy之前要先给python安装mysql驱动

它既支持原生SQL又支持ORM

实现代码:

create_engine("数据库类型+数据库驱动://数据库用户名:数据库密码@IP地址:端口/数据库",其他参数)

echo=True是开启调试,这样当我们执行文件的时候会提示相应的文字。

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()

3、 MySQL-python

因为它不兼容Python3.x,所以现在已经被MySQLclient取代

# _*_ coding: utf-8 _*_

import MySQLdb

# 创建连接

conn = MySQLdb.connect(

host='10.181.68.153',# 你的MySQL服务器地址

port=3357,# 端口

user='root',# 访问数据库服务的用户名和密码

passwd='Xb123456@',

db='xiaob_new',# 数据库名称

charset='utf8' # 如果去掉这句话,下面的一等奖会展示乱码

)

# 执行查询

cur = conn.cursor()

cur.execute("select * from award") # 执行查询

results = cur.fetchall() # 拿到返回结果

for re in results: # 循环并打印拿到的结果

print(re)

4、peewee

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

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)

如果觉得有用请给我点个赞吧,谢谢你的支持,ღ( ´・ᴗ・` )❥

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容