轉載本文章請標明作者和出處
本文出自《Darwin的程序空間》
vlog
- 時間:2020年03月08日-2020年03月09日 ——————晚上三個小時
- 學習方式:菜鳥教程,博客,百度
- 完成內容:使用pymysql對mysql數據庫進行增刪改查,並封裝一個數據庫操作類,最後寫一個腳本往數據庫導入100W的數據
- 博客目的:總結歸納,當然要能幫助其他剛學習Python的童鞋,不勝榮幸
- 人物:一個心血來潮學習Python的JAVA程序員
正文
操作mysql
安裝mysql
首先想操作數據庫,必須得現在本機或者遠程雲服務器上安裝一個MYSQL,這裏筆者是在本地起了一個docker,跑了一個mysql5.7的容器;
這類的教程網上很多,這裏就不多做聲明,如果讀者沒有學過docker也可以使用傳統的安裝方式,mysql的安裝還是很簡單的,傻瓜式安裝即可;
安裝後我們可以使用navicat連接上即算成功;
安裝pymysql
-
使用如下命令
pip install PyMySQL
-
如果這種方式行不通的話,可以現在tar.gz包,解壓後使用python setup.py install命令安裝pymysql模塊
使用pymysql簡單的操作數據庫
-
操作步驟
- 首先我們要使用connect函數指定ip、用戶名、密碼、數據庫來獲取數據庫連接對象;
- 然後使用數據庫連接對象獲取遊標;(可以指定遊標查詢獲取數據的類型,默認爲元組,這裏可以指定爲字典conn.cursor(cursor=cursors.DictCursor))
- 使用遊標來執行原生的sql語句(用慣了SpringDataJpa的我,好久沒有整過原生的sql了),這裏會返回影響的數據庫數據的條數
- 使用遊標的fetch系列的方法來獲取結果;
- 如果對數據庫有修改操作,需要使用連接對象提交事務;
- 關閉遊標和連接的資源,調用close方法;
-
代碼(使用pymysql獲取數據庫版本和創建數據庫的demo)
- 查詢數據庫版本
from pymysql import * # 獲取數據庫的連接 conn = connect("192.168.100.145", "root", "123", "JD") # 獲取有表對象 cursors = conn.cursor() # 執行查詢數據庫版本的SQL語句 cursors.execute("select version()") # 獲取一條結果 version = cursors.fetchone() # 打印結果 print("Database version is %s" % version) # 關閉遊標 cursors.close() # 關閉數據的連接 conn.close()
- 創建數據庫
from pymysql import * conn = connect("192.168.100.145", "root", "123", "JD") cursors = conn.cursor() sql = "CREATE TABLE EMPLOYEE ( \ FIRST_NAME CHAR(20) NOT NULL, \ LAST_NAME CHAR(20), \ AGE INT, \ SEX CHAR(1),\ INCOME FLOAT )" cursors.execute(sql) cursors.close() conn.close()
- 查詢數據庫版本
使用pymysql完成增刪改查四大基本操作
- 增
from pymysql import *
conn = connect(“192.168.100.145”, “root”, “123”, “JD”)
cursors = conn.cursor()
SQL 插入語句
-
增
from pymysql import * conn = connect("192.168.100.145", "root", "123", "JD") cursors = conn.cursor() # SQL 插入語句 sql = "INSERT INTO EMPLOYEE(FIRST_NAME, \ LAST_NAME, AGE, SEX, INCOME) \ VALUES ('%s', '%s', %s, '%s', %s)" % \ ('Mac', 'Mohan', 20, 'M', 2000) try: # 執行sql語句 cursors.execute(sql) # 執行sql語句 conn.commit() except Exception as res: # 發生錯誤時回滾 conn.rollback() print("error %s" % res) cursors.close() conn.close()
-
查
from pymysql import * conn = connect("192.168.100.145", "root", "123", "JD") cursors = conn.cursor() # SQL 查詢語句 sql = "SELECT * FROM EMPLOYEE \ WHERE INCOME > %s" % "1000" try: # 執行SQL語句 cursors.execute(sql) # 獲取所有記錄列表 results = cursors.fetchall() for row in results: print(type(row)) # <class 'tuple'> fname = row[0] lname = row[1] age = row[2] sex = row[3] income = row[4] # 打印結果 print("fname=%s,lname=%s,age=%s,sex=%s,income=%s" % \ (fname, lname, age, sex, income)) except: print("Error: unable to fetch data") cursors.close() conn.close()
-
改
from pymysql import * conn = connect("192.168.100.145", "root", "123", "JD") cursors = conn.cursor() # SQL 更新語句 sql = "UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = '%c'" % ('M') try: # 執行SQL語句 row = cursors.execute(sql) print("一共影響了%d行" % row) # 提交到數據庫執行 conn.commit() except Exception as res: # 發生錯誤時回滾 conn.rollback() print("error %s" % res) cursors.close() conn.close()
-
刪
from pymysql import * conn = connect("192.168.100.145", "root", "123", "JD") cursors = conn.cursor() # 使用cursor()方法獲取操作遊標 cursor = conn.cursor() # SQL 刪除語句 sql = "DELETE FROM EMPLOYEE WHERE AGE > %s" % "20" try: # 執行SQL語句 cursor.execute(sql) # 提交修改 conn.commit() except Exception as res: # 發生錯誤時回滾 conn.rollback() print("error %s" % res) cursors.close() conn.close()
封裝數據庫操作對象
-
with as用法
在Python中使用try…except…finally的語句太過囉嗦,不符合Python語言編程的哲學,果然,經過往上搜索之後,發現了一個簡單的語法with…as語句在創建類的時候,在內部實現__enter__方法,with語句一開始就會執行這個方法,
再實現__exit__方法,退出with代碼塊的時候會自動執行這個方法。- 例子(來源於網絡)
class A: def __enter__(self): print('with語句開始') return self # 返回self就是把這個對象賦值給as後面的變量 def __exit__(self, exc_type, exc_val, exc_tb): print('with語句結束') with A() as f: print('IG牛批') print(f) print('IG真的牛批') 結果: with語句開始 IG牛批 <__main__.A object at 0x0000027B4D1596D8> with語句結束 IG真的牛批
- 例子(來源於網絡)
-
然後我們就可以使用這個語法和麪向對象的知識,來封裝一個數據庫操作的類
from pymysql import * class DB(object): def __init__(self, ip="192.168.100.145", username="root", password="123", database_name="JD"): self.conn = connect(ip, username, password, database_name) self.cursor = self.conn.cursor(cursor=cursors.DictCursor) def __enter__(self): """ 這個方法的返回值將被賦值給as關鍵字後面的變量 """ return self.cursor def __exit__(self, exc_type, exc_val, exc_tb): """ 當with後面的代碼塊全部被執行完之後,將調用前面返回對象的__exit__()方法 """ self.conn.commit() self.cursor.close() self.conn.close() if __name__ == '__main__': with DB() as db: db.execute("select version()") version = db.fetchone() print(type(version)) print(version)
百萬數據導入
-
代碼
from pymysql import * import time conn = connect("192.168.2.89", "root", "123", "console_hy") cursor = conn.cursor() start = time.time() i = 0 try: while i < 1000000: sql = "INSERT INTO EMPLOYEE(FIRST_NAME, \ LAST_NAME, AGE, SEX, INCOME) \ VALUES ('%s', '%s', %s, '%s', %s)" % \ ('Mac', 'Mohan', 20, 'M', i) # 執行sql語句 cursor.execute(sql) i += 1 # 執行sql語句 conn.commit() except Exception as res: # 發生錯誤時回滾 conn.rollback() print("error %s" % res) cursor.close() conn.close() end = time.time() print("100W數據用時%ds" % (int(end) - int(start)))
-
耗時
- 100W數據用時395s