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')
相關文章
相關標籤/搜索