Python *** 作 MySQL 的5种方式

Python  *** 作 MySQL 的5种方式,第1张

1、MySQLdb

# 前置条件

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 = "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

# 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

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

4、peewee

pip install peewee

import peewee

from peewee import *

db = MySQLDatabase('testdb', user = 'root', passwd = 'pythontab.com')

class Book(peewee.Model):

author = peewee.CharField()

title = peewee.TextField()

class Meta:

database = db

Book.create_table()

book = Book(author = "pythontab", title = 'pythontab is good website')

book.save()

for book in Book.filter(author = "pythontab"):

print(book.title)

5、SQLAlchemy

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

MySQL 是目前使用最广泛的数据库之一,它有着良好的性能,能够跨平台,支持分布式,能够承受高并发。下载地址: MySQL :: Download MySQL Community Server 安装参考: 图解MySQL5.7.20免安装版配置方法-百度经验 (baidu.com)

Python 大致有如下 5 种方式 *** 作 MySQL。

先使用如下建表语句创建一张简单的数据库表。

2.1 mysqlclient

执行 pip install mysqlclient 进行安装,看一下具体 *** 作

新增

查询

cursor 查看方法

修改

删除

2.2 PyMySQL

执行 pip install pymysql 进行安装,使用方式与 mysqlclient 基本类似。

2.3 peewee

执行 pip install peewee 进行安装,看一下具体 *** 作

定义映射类

新增

查询

修改

删除

2.4 SQLAlchemy

执行 pip install sqlalchemy 进行安装,看一下具体 *** 作。

定义映射类

新增

查询

修改

删除

Python学习日记


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/6137945.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-03-16
下一篇 2023-03-16

发表评论

登录后才能评论

评论列表(0条)

保存