Python3呼叫MySQL資料庫中的資料

2021-08-17 20:16:29 字數 1318 閱讀 7851

在學習《designing machine learning systems with python》(中文名《機器學習系統設計——python語言實現》)一書中,在第三章第二節第四小節(p67)讀取mysql資料庫中資料的**中。使用的python包是mysql包,但是這個包只支援python2.7以下版本。原話是

mysql-3.23 through 5.5 and python-2.4 through 2.7 are currently supported. python-3.0 will be supported in a future release. pypy is supported.

但是就我找到的版本中這已經是最新的mysql版本了。所以只好換乙個python包了。我選擇的是pymysql包。

安裝過程就是pip install pymysql這沒什麼好說的。安裝完成後,仿照在網上找到的例子(正確做法是仿照官網上的example來修改,但是我一看官網給出的例子有一丟丟長,所以就在網上隨便找到了另乙個例子)

修改後,原來的**就換成了

import pymysql   # not support in python3

# from pymysql.connector import errorcode

cnx = pymysql.connect(user='root', password='password', database='world')

cursor = cnx.cursor()

query = ('select * from city where population > 1000000 order by population')

cursor.execute(query)

worldlist =

for (city) in cursor:

cursor.close()

cnx.close()

在最後在加上乙個輸出語句

print

(worldlist)

執行無誤,輸出結果(結果很多,我用省略號代替了)

[['zapopan', 1002239], ['napoli', 1002619], ['perm', 1009700], ['odesa', 1011000], ['rostov-na-donu', 1012700], ['birmingham', 1013000], ..., ['mumbai (bombay)', 10500000]]
然後去mysql資料庫中檢視下,資料正確。

日常Python 3 呼叫函式

任務.輸出每日一貼 在idle中建立乙個名為function tips.py的檔案,然後在該檔案中建立乙個名稱為function tips的函式,在該函式中,從勵志文字列表中獲取一條勵志文字並輸出,最後再呼叫函式function tips 如下 coding gbk def function tip...

python3呼叫http介面

最近在寫python呼叫介面的服務,寫了乙個呼叫介面的函式,如下 param inputdata 單個樣本的輸入引數,是json格式的資料 return 單個樣本的探真查詢變數結果資料 呼叫介面 介面有正確的資料才讀入,否則為空 if res code 0000 res data json.load...

Python3呼叫Google翻譯

import urllib.request from handlejs import py4js def open url url headers req urllib.request.request url url,headers headers response urllib.request.u...