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

Python3 MySQL 数据库链接

python3使用mysql做为数据库,安装pymysql做为驱动,而后安装sqlalchemy框架html

 

PyMySQL 驱动 

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

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

 

安装:

$ python3 -m pip install PyMySQL

 

 

 

历史:python mysql各种驱动简介

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

因而出现了:mysqlclient,彻底兼容mysqlldb,支持python3和2。github

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

 

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

前提:express

  • 建立了用户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语句)api

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')
相关文章
相关标签/搜索