python執(zhí)行數(shù)據(jù)庫(kù)的查詢(xún)操作實(shí)例講解
1、fetchone該方法獲取下一個(gè)查詢(xún)結(jié)果集。結(jié)果集是一個(gè)對(duì)象。
2、fetchall接收全部的返回結(jié)果行。
3、rowcount這是一個(gè)只讀屬性,并返回執(zhí)行execute方法后影響的行數(shù)。
實(shí)例
from pymysql import * def main(): # 創(chuàng)建Connection連接 conn = connect(host='localhost',port=3306,user='root',password='mysql',database='jing_dong',charset='utf8') # 獲得Cursor對(duì)象 cs1 = conn.cursor() # 執(zhí)行select語(yǔ)句,并返回受影響的行數(shù):查詢(xún)一條數(shù)據(jù) count = cs1.execute('select id,name from goods where id>=4') # 打印受影響的行數(shù) print("查詢(xún)到%d條數(shù)據(jù):" % count) for i in range(count): # 獲取查詢(xún)的結(jié)果 result = cs1.fetchone() # 打印查詢(xún)的結(jié)果 print(result) # 元組 (1, '張三', 20, '男') # 獲取查詢(xún)的結(jié)果 # 關(guān)閉Cursor對(duì)象 cs1.close() conn.close() if __name__ == '__main__': main()
實(shí)例擴(kuò)展:
#! /usr/bin/python # filename conn.py import MySQLdb# 載入連接數(shù)據(jù)庫(kù)模塊 try: # 嘗試連接數(shù)據(jù)庫(kù) conn = MySQLdb.connect("localhost","root","www","yao",charset="utf8") # 定義連接數(shù)據(jù)庫(kù)的信息 except MySQLdb.OperationalError, message: # 連接失敗提示 print "link error" cursor=conn.cursor() #定義連接對(duì)象 cursor.execute("select * from user") #使用cursor提供的方法來(lái)執(zhí)行查詢(xún)語(yǔ)句 data=cursor.fetchall()#使用fetchall方法返回所有查詢(xún)結(jié)果 print data #打印查詢(xún)結(jié)果 cursor.close()#關(guān)閉cursor對(duì)象 conn.close() #關(guān)閉數(shù)據(jù)庫(kù)鏈接
到此這篇關(guān)于python執(zhí)行數(shù)據(jù)庫(kù)的查詢(xún)操作實(shí)例講解的文章就介紹到這了,更多相關(guān)python如何執(zhí)行數(shù)據(jù)庫(kù)查詢(xún)操作內(nèi)容請(qǐng)搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來(lái)源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來(lái)源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來(lái)源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來(lái),僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。