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

 

 



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM