python3 -- pymysql fetch0ne fetchall fetchmany的用法


1、fetchall()

# 連接數據庫
def main():

    # 連接數據庫
    db = pymysql.connect(host='192.168.0.1', port=3306, user='root', 
                        password='root', db='user', charset='utf8')

    print('連接數據庫')
    print('開始數據查詢')
    
    # 執行方法
    query_(db)
    
    print('結束數據庫查詢')
    # 關閉數據庫連接
    db.close()
    print('關閉數據庫')

# 查詢
def query_(db): # 使用 cursor() 方法創建一個游標對象 cursor cursor = db.cursor() # sql查詢語句 sql = "select user_info from user_info where user_id=1" # 執行 SQL 查詢, 返回受影響的行數 row_count = cursor.execute(sql) # 獲取數據 results_db = cursor.fetchall() # results_db 類型:元祖;eg:((字段1, 字段2, 字段。。。, 字段n), (), ... ()) # 轉儲至文件的結果集合 res_lst = [] if results_db: # 計數 count = 0 # 遍歷處理 for row in results_db: # 計數自增 count += 1
       # 處理邏輯
        # 匯總至結果集 res_lst.append(row) else: print('數據庫查詢結果為空') # 關閉查詢 cursor.close()

2、fetchone():

# 連接數據庫
def main():

    # 連接數據庫
    db = pymysql.connect(host='192.168.11.1', port=3306, user='root', 
                        password='root', db='user', charset='utf8')

    print('連接數據庫')
    print('開始數據查詢')
    
    # 執行方法
    query_(db)
    
    print('結束數據庫查詢')
    # 關閉數據庫連接
    db.close()
    print('關閉數據庫')

# 查詢處理
def query_(db):
    # 使用 cursor() 方法創建一個游標對象 cursor
    cursor = db.cursor()

    # sql查詢語句
    sql = "select user_id from user_info where user_id=1"

    # 執行 SQL 查詢
    row_count = cursor.execute(sql)

    # 獲取數據行數
    print("查詢到%d條數據:" % row_count)
    
    with open("all_field_bak", 'w', encoding='utf8') as f:
        writer = csv.writer(f)

        for i in range(row_count):
            # 獲取查詢結果
            res = cursor.fetchone()
            #print(res)
            #print(type(res))

            # 寫入文件
            writer.writerow(res)

    # 關閉查詢
    cursor.close()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM