本文全部的實驗基於mysql的python數據庫裏的test表(估計給數據庫起名爲python的人也就只有我了),test表結構以下:python
能夠把connection理解成一個事務,事務的最終有兩種操做:提交connection.commit()和回滾connection.rollback()mysql
import pymysql import time # 鏈接數據庫 connection = pymysql.connect(host='127.0.0.1', port=3306, database='python', user='root', password='root', charset='utf8') try: with connection.cursor() as cursor: sql = "insert into test(str, num, time) values(%s, %s, %s)" # 插入整數也用%s for i in range(10): cursor.execute(sql, ('hello,world', i, time.strftime('%y-%m-%d %H-%M-%S'))) # 這裏給的整數i connection.commit() # 提交數據庫添加操做 with connection.cursor() as cursor: sql = "select id, str from test where num > %s" cursor.execute(sql, (3,)) # 每次取結果集,cursor將會向後移動 print(cursor.fetchone()) # 取一行結果集 print(cursor.fetchmany(2)) # 取若干行 print(cursor.fetchall()) # 取全部行 except Exception as e: print(e) print('數據庫操做發生異常') connection.rollback() else: print('數據庫操做成功') finally: connection.close()
1. 每次調用execute()後都會返回受影響的行數,一樣能夠經過cursor.rowcount進行獲取sql
2. fetch()默認以元組的形式返回查詢結果,能夠在建立cursor的時候傳入參數,設置fetch()的查詢結果以字典的形式返回,這樣就能夠在查詢結果裏,根據key來索引value了數據庫
cursor = connection.cursor(cursor=pymysql.cursors.DictCursor)