1. 程式人生 > >Python 資料庫,操作mysql,查詢,fetchone(), fetchmany(), fetchall()

Python 資料庫,操作mysql,查詢,fetchone(), fetchmany(), fetchall()

 

demo.py(查詢,取出一條資料,fetchone):

from pymysql import *


def main():
    # 建立Connection連線
    conn = connect(host='localhost',port=3306,user='root',password='mysql',database='jing_dong',charset='utf8')
    # 獲得Cursor物件
    cs1 = conn.cursor()
    # 執行select語句,並返回受影響的行數:查詢一條資料
    count = cs1.execute('select id,name from goods where id>=4')
    # 列印受影響的行數
    print("查詢到%d條資料:" % count)

    for i in range(count):
        # 獲取查詢的結果
        result = cs1.fetchone()
        # 列印查詢的結果
        print(result)  # 元組 (1, '張三', 20, '男')
        # 獲取查詢的結果

    # 關閉Cursor物件
    cs1.close()
    conn.close()


if __name__ == '__main__':
    main()
    
    

demo.py(查詢,取出多條資料,fetchmany,fetchall):

from pymysql import *

def main():
    # 建立Connection連線
    conn = connect(host='localhost',port=3306,user='root',password='mysql',database='jing_dong',charset='utf8')
    # 獲得Cursor物件
    cs1 = conn.cursor()
    # 執行select語句,並返回受影響的行數:查詢一條資料
    count = cs1.execute('select id,name from goods where id>=4')
    # 列印受影響的行數
    print("查詢到%d條資料:" % count)

    # for i in range(count):
    #     # 獲取查詢的結果
    #     result = cs1.fetchone()   # 取出一條記錄,返回元組。
    #     # 列印查詢的結果
    #     print(result)
    #     # 獲取查詢的結果

    # 獲取所有記錄
    result = cs1.fetchall()  # fetchmany(3)  取出3條記錄,返回二維元組。
    print(result)   # 二維元組

    # 關閉Cursor物件
    cs1.close()
    conn.close()

if __name__ == '__main__':
    main()