python3使用mysql做为数据库,安装pymysql做为驱动,而后安装sqlalchemy框架html
参考教程https://www.runoob.com/python3/python3-mysql.htmlpython
以及PyMySQL文档https://pymysql.readthedocs.io/en/latest/modules/cursors.htmlmysql
$ python3 -m pip install PyMySQL
python版本早期用jmysqlLdb或叫作mysql-python,但年久失修。git
因而出现了:mysqlclient,彻底兼容mysqlldb,支持python3和2。github
又出现了pymysql,是纯python打造,接口和pyhon-mysql兼容,而且安装方便,支持2,3。git✨5.6k sql
上一章讲解了建立用户和受权。本章根据参考教程,了解如何用python的包链接mysql数据库,并对数据进行操做。数据库
前提:express
mysql> create table employee( -> first_name varchar(20), -> last_name varchar(20), -> age int, -> sex enum("man", 'woman'), -> income decimal(10,2));
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()
⚠️:
http://zetcode.com/db/sqlalchemy/intro/
也推荐这篇知乎:https://zhuanlan.zhihu.com/p/27400862
咱们使用python对数据库的数据进行处理,有3种写sql语句的方法:
sql expression language API能够创建sql queries, 经过使用python object和operators。它是纯sql的抽象。
orm框架(对象关系映射):表明了用户定义的类的一系列方法。它是基于sql expression language的。
由于,原生的sql写起来麻烦因此诞生了不少封装wrapper包和orm框架。提升了写代码的速度,同时兼容多类数据库,付出的代价是性能上的一些损失。
例如:
任何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
# 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')