Python3 MySQL 数据库连接:安装pymysql(mysql数据库驱动), sqlalchemy(ORM框架)。

Python3 MySQL 数据库连接

python3使用mysql作为数据库,安装pymysql作为驱动,然后安装sqlalchemy框架

 

PyMySQL 驱动 

 参考教程https://www.runoob.com/python3/python3-mysql.html

 以及PyMySQL文档https://pymysql.readthedocs.io/en/latest/modules/cursors.html

安装:

$ python3 -m pip install PyMySQL

历史:python mysql各类驱动简介

python版本早期用jmysqlLdb或叫做mysql-python,但年久失修。

于是出现了:mysqlclient,完全兼容mysqlldb,支持python3和2。

又出现了pymysql,是纯python打造,接口和pyhon-mysql兼容,并且安装方便,支持2,3。git✨5.6k 

上一章讲解了创建用户和授权。本章根据参考教程,了解如何用python的包连接mysql数据库,并对数据进行操作。

前提:

  • 创建了用户testuser, 并授权。
  • 创建了testdb数据库。并创建了表employee
  • EMPLOYEE表字段为 FIRST_NAME, LAST_NAME, AGE, SEX 和 INCOME。
  • ⚠️需要安装pymysql包:  $ python3 -m pip install PyMySQL
mysql> create table employee(
    -> first_name varchar(20),
    -> last_name varchar(20),
    -> age int,
    -> sex enum("man", 'woman'),
    -> income decimal(10,2));

创建临时文件linshi.py,  下面的代码演示了如何打开数据库,关闭数据库。

import pymysql

db = pymysql.connect(host='localhost',user= 'testuser', password="", db='testdb')

# 创建一个游标对象
cursor = db.cursor()

cursor.execute("select version();")

data = cursor.fetchone()

print("database version %s" % data)

db.close()

执行脚本输出: database version 8.0.18

下面的代码演示了如何创建数据库表

(使用原生sql语句)

import pymysql

db = pymysql.connect(host='localhost',user= 'testuser', password="", db='testdb')

# 创建一个游标对象
cursor = db.cursor()

cursor.execute("drop table if exists employee;")

sql = """CREATE TABLE EMPLOYEE (
         FIRST_NAME  CHAR(20) NOT NULL,
         LAST_NAME  CHAR(20),
         AGE INT,
         SEX CHAR(1),
         INCOME FLOAT )"""
         
cursor.execute(sql)
cursor.execute("desc employee")
data = cursor.fetchall()

for i in range(0, len(data)):
    print(data[i])

db.close()

⚠️:

  1. cursor对象的方法有很多fetchall()返回一个tuple。
  2. 一定要关闭数据库。

SQLAlchemy框架

http://zetcode.com/db/sqlalchemy/intro/

也推荐这篇知乎:https://zhuanlan.zhihu.com/p/27400862

前提知识:

我们使用python对数据库的数据进行处理,有3种写sql语句的方法:

  • raw sql:  纯sql
  • sql expression language
  • orm框架

sql expression language API可以建立sql queries, 通过使用python object和operators。它是纯sql的抽象。

orm框架(对象关系映射):代表了用户定义的类的一系列方法。它是基于sql expression language的。

周边:各类ORM框架:

因为,原生的sql写起来麻烦所以诞生了很多封装wrapper包和orm框架。提高了写代码的速度,同时兼容多类数据库,付出的代价是性能上的一些损失。

例如:

  1. peewee小的orm框架,git✨是7.1k。https://github.com/coleifer/peewee
  2. sqlalchemy, 在编程领域使用广泛,借助pymysql等第三方库。因此既支持原生sql也支持orm。git✨只1.7k, 开发活跃

组件

Engine连接。

任何sqlalchemy程序的开始点。是数据库和它的api的抽象。把sql声明从sqlalchemy传递到database

使用 create_engine()函数创建一个engine, 它被用于直接连接数据库,或被传递给一个Session对象,然后和orm框架配合操作。

文档:https://docs.sqlalchemy.org/en/13/core/engines.html

create_engine()格式

dialect+driver://username:password@host:port/database
  • dialect是指sqlite, mysql,oracle等。
  • driver是DBAPI的名字。用于连接数据库的。
  • url中的密码需要url encoded。文档中有编码的例子使用urllib模块。
# PyMySQL
engine = create_engine('mysql+pymysql://scott:tiger@localhost/foo')

例子:

import pandas as pd
import sqlalchemy

#进入根数据库,密码是123456,然后进入数据库test1
engine = sqlalchemy.create_engine('mysql+pymysql://root:123456@localhost:3306/test1')

#pandas包有一个read_sql命令
pd.read_sql('select * from orderinfo', engine)
# 从一个文件读取数据,然后写入到数据库: df
= pd.read_csv('order_info_utf.csv',names=['orderid','userid','ispaid','price','paidtime']) # 还有参数if_exists,表示有则插入 df.to_sql('orderinfo',engine,index=False,if_exists='append')

原文地址:https://www.cnblogs.com/chentianwei/p/12103298.html