python和mysql互動操作例項詳解【基於pymysql庫】
本文例項講述了python和mysql互動操作。分享給大家供大家參考,具體如下:
python要和mysql互動,我們利用pymysql
這個庫。
下載地址:
https://github.com/PyMySQL/PyMySQL
安裝(注意cd到我們專案的虛擬環境後):
cd 專案根目錄/abc/bin/ #執行 ./python3 -m pip install pymysql
稍等片刻,就會把pymysql
庫下載到專案虛擬環境abc/lib/python3.5/site-packages中。(注意我專案是這個路徑,你的不一定)
文件地址:
http://pymysql.readthedocs.io/en/latest/
使用:
import pymysql.cursors # 連線資料庫 connection = pymysql.connect(host='localhost',user='root',password='root',db='test',charset='utf8mb4',cursorclass=pymysql.cursors.DictCursor) try: with connection.cursor() as cursor: # Read a single record sql = "SELECT * From news" cursor.execute(sql) result = cursor.fetchone() print(result) # {'id': 1,'title': '本機新聞標題'} finally: connection.close()
我們連上了本地資料庫test,從news表中取資料,資料結果為{'id': 1,'title': '本機新聞標題'}
返回的結果是字典型別,這是因為在連線資料庫的時候我們是這樣設定的:
# 連線資料庫 connection = pymysql.connect(host='localhost',cursorclass=pymysql.cursors.Cursor)
我們把cursorclass
設定的是:pymysql.cursors.DictCursor
。
字典遊標,所以結果集是字典型別。
我們修改為如下:
cursorclass=pymysql.cursors.Cursor
結果集如下:
(1,'本機新聞標題')
變成了元組型別。我們還是喜歡字典型別,因為其中包含了表字段。
Cursor物件
主要有4種:
Cursor 預設,查詢返回list或者tuple
DictCursor 查詢返回dict,包含欄位名
SSCursor 效果同Cursor,無快取遊標
SSDictCursor 效果同DictCursor,無快取遊標。
插入
try: with connection.cursor() as cursor: sql = "INSERT INTO news(`title`)VALUES (%s)" cursor.execute(sql,["今天的新聞"]) # 手動提交 預設不自動提交 connection.commit() finally: connection.close()
一次性插入多條資料
try: with connection.cursor() as cursor: sql = "INSERT INTO news(`title`)VALUES (%s)" cursor.executemany(sql,["新聞標題1","新聞標題2"]) # 手動提交 預設不自動提交 connection.commit() finally: connection.close()
注意executemany()
有別於execute()
。
sql繫結引數
sql = "INSERT INTO news(`title`)VALUES (%s)" cursor.executemany(sql,"新聞標題2"])
我們用%s
佔位,執行SQL的時候才傳遞具體的值。上面我們用的是list型別:
["新聞標題1","新聞標題2"]
可否用元組型別呢?
cursor.executemany(sql,("元組新聞1","元組新聞2"))
同樣成功插入到資料表了。
把前面分析得到的基金資料入庫
建立一個基金錶:
CREATE TABLE `fund` ( `code` varchar(50) NOT NULL,`name` varchar(255),`NAV` decimal(5,4),`ACCNAV` decimal(5,`updated_at` datetime,PRIMARY KEY (`code`) ) COMMENT='基金錶';
準備插入SQL:
複製程式碼 程式碼如下:INSERT INTO fund(`code`,`name`,`NAV`,`ACCNAV`,`updated_at`)VALUES (%(code)s,%(name)s,%(NAV)s,%(ACCNAV)s,%(updated_at)s)
注意%(code)s
這種佔位符,要求我們執行這SQL的時候傳入的引數必須是字典資料型別。
MySQL小知識:
在插入的時候如果有重複的主鍵,就更新
insert into 表名 xxxx ON duplicate Key update 表名
我們這裡要準備執行的SQL就變成這樣了:
INSERT INTO fund(code,name,NAV,ACCNAV,updated_at)VALUES (%(code)s,%(updated_at)s) ON duplicate Key UPDATE updated_at=%(updated_at)s,NAV=%(NAV)s,ACCNAV=%(ACCNAV)s;
1、回顧我們前面分析處理的基金網站資料
//www.jb51.net/article/162452.htm
#... codes = soup.find("table",id="oTable").tbody.find_all("td","bzdm") result = () # 初始化一個元組 for code in codes: result += ({ "code":code.get_text(),"name":code.next_sibling.find("a").get_text(),"NAV":code.next_sibling.next_sibling.get_text(),"ACCNAV":code.next_sibling.next_sibling.next_sibling.get_text() },)
最後我們是把資料存放在一個result
的元組裡了。
我們列印這個result
可以看到:
複製程式碼 程式碼如下:({'code': '004223','ACCNAV': '1.6578','name': '金信多策略精選靈活配置','NAV': '1.6578'},...}
元組裡每個元素 都是字典。
看字典是不是我們資料表的欄位能對應了,但還少一個updated_at
欄位的資料。
2、我們把分析的網頁資料重新處理一下
from datetime import datetime updated_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S") result = () # 初始化一個元組 for code in codes: result += ({ "code":code.get_text(),"ACCNAV":code.next_sibling.next_sibling.next_sibling.get_text(),"updated_at":updated_at },)
3、最後插入的程式碼
try: with connection.cursor() as cursor: sql = """INSERT INTO fund(`code`,%(updated_at)s) ON duplicate Key UPDATE `updated_at`=%(updated_at)s,`NAV`=%(NAV)s,`ACCNAV`=%(ACCNAV)s""" cursor.executemany(sql,result) # 手動提交 預設不自動提交 connection.commit() finally: connection.close()
4、完整的分析html內容(基金網站網頁內容),然後插入資料庫程式碼:
from bs4 import BeautifulSoup import pymysql.cursors from datetime import datetime # 讀取檔案內容 with open("1.txt","rb") as f: html = f.read().decode("utf8") f.close() # 分析html內容 soup = BeautifulSoup(html,"html.parser") # 所有基金編碼 codes = soup.find("table","bzdm") updated_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S") result = () # 初始化一個元組 for code in codes: result += ({ "code":code.get_text(),) # 連線資料庫 connection = pymysql.connect(host='localhost',cursorclass=pymysql.cursors.Cursor) try: with connection.cursor() as cursor: sql = """INSERT INTO fund(`code`,result) # 手動提交 預設不自動提交 connection.commit() finally: connection.close()
更多關於Python相關內容感興趣的讀者可檢視本站專題:《Python常見資料庫操作技巧彙總》、《Python數學運算技巧總結》、《Python資料結構與演算法教程》、《Python函式使用技巧總結》、《Python字串操作技巧彙總》、《Python入門與進階經典教程》及《Python檔案與目錄操作技巧彙總》
希望本文所述對大家Python程式設計有所幫助。