python 使用mysql.connector 查詢數(shù)據(jù)
使用mysql.connector 操作mysql數(shù)據(jù)庫(kù),首先需要?jiǎng)?chuàng)建連接,第二步是獲得cursor,想要執(zhí)行sql語句,需要調(diào)用cursor的execute方法。在上一篇教程中,我們已經(jīng)向city表里寫入了幾條數(shù)據(jù),現(xiàn)在演示如何獲取這些數(shù)據(jù)
1. fetchall獲取查詢的全部數(shù)據(jù)
import mysql.connector
# 第一步,創(chuàng)建連接
mydb = mysql.connector.connect(
host="10.110.30.3", # 數(shù)據(jù)庫(kù)主機(jī)地址
user="flink_user", # 數(shù)據(jù)庫(kù)用戶名
passwd="123456", # 數(shù)據(jù)庫(kù)密碼
port=6606,
database='flink_db'
)
sql = "select * from city"
mycursor = mydb.cursor() # 第二步,創(chuàng)建cursor
mycursor.execute(sql) # 第三步,執(zhí)行sql
datas = mycursor.fetchall() # 第四步, fetchall 獲取全部數(shù)據(jù)
for data in datas:
print(data)
程序輸出結(jié)果
(11, '北京')
(12, '上海')
(13, '廣州')
(14, '深圳')
2. fetchone 和 fetchmany
fetchone 從查詢獲取到的數(shù)據(jù)集合中取出一條數(shù)據(jù)
data = mycursor.fetchone() # fetchone 獲取集合中的一條
print(data) # (11, '北京')
fetchmany 可以獲取多條數(shù)據(jù),需要指定獲取數(shù)據(jù)條目的數(shù)量
data = mycursor.fetchmany(2) # fetchmany 獲取2兩條數(shù)據(jù)
print(data) # [(11, '北京'), (12, '上海')]
3. 獲取字典形式的返回值
前面的例子里,查詢獲得數(shù)據(jù)都是以元組的形式返回的,這種格式不利于查看和處理,最受歡迎的格式是字典格式,這種格式需要在創(chuàng)建cursor時(shí)指定dictionary
sql = "select * from city"
mycursor = mydb.cursor(dictionary=True) # 第二步,創(chuàng)建cursor
mycursor.execute(sql) # 第三步,執(zhí)行sql
data = mycursor.fetchone() # fetchone 獲取集合中的一條
print(data) # {'id': 11, 'name': '北京'}
除了字典格式,還可以使用named_tuple格式
sql = "select * from city"
mycursor = mydb.cursor(named_tuple=True) # 第二步,創(chuàng)建cursor
mycursor.execute(sql) # 第三步,執(zhí)行sql
data = mycursor.fetchone() # fetchone 獲取集合中的一條
print(data) # Row(id=11, name='北京')評(píng)論
圖片
表情
