本模塊爲python第三方模塊,須要單獨安裝。做用爲調用mysql接口執行模塊python
pip3 install pyMySqlmysql
操做步驟:sql
#!/usr/bin/python3 import pymysql # 打開數據庫鏈接 db = pymysql.connect("10.1.80.200", "alex", "alex", "ip") # 使用 cursor() 方法建立一個遊標對象 cursor cursor = db.cursor() # 使用 execute() 方法執行 SQL 查詢 cursor.execute("SELECT VERSION()") # 使用 fetchone() 方法獲取單條數據. data = cursor.fetchone() print("Database version : %s " % data) # 關閉數據庫鏈接 db.close()
一、執行sql數據庫
#!/usr/bin/env python # -*- coding:utf-8 -*- import pymysql # 建立鏈接 conn = pymysql.connect(host='10.1.80.200', port=3306, user='alex', passwd='alex', db='cs') # 建立遊標 cursor = conn.cursor() # 執行SQL,創建一個測試表 effect_row = cursor.execute("create table cstable (id int,sex char(1),name char(10));") # 提交,否則沒法保存新建或者修改的數據 conn.commit() # 關閉遊標 cursor.close() # 關閉鏈接 conn.close()
二、獲取新建立數據自增ID編程
#!/usr/bin/env python # -*- coding:utf-8 -*- import pymysql # 建立鏈接 conn = pymysql.connect(host='10.1.80.200', port=3306, user='alex', passwd='alex', db='cs') # 建立遊標 cursor = conn.cursor() # 執行SQL cursor.execute("select * from cstable;") # 獲取前n行數據 # row_2 = cursor.fetchmany(3) # 獲取全部數據 # row_3 = cursor.fetchall() # 獲取第一行數據 row_1 = cursor.fetchone() # 打印第一行數據 print(row_1) # 關閉遊標 cursor.close() # 關閉鏈接 conn.close()
三、更新mysql表中數據測試
對於支持事務的數據庫, 在Python數據庫編程中,當遊標創建之時,就自動開始了一個隱形的數據庫事務。fetch
commit()方法遊標的全部更新操做,rollback()方法回滾當前遊標的全部操做。每個方法都開始了一個新的事務。spa
#!/usr/bin/python3 import pymysql # 打開數據庫鏈接 db = pymysql.connect("10.1.80.200", "alex", "alex", "ip") # 使用 cursor() 方法建立一個遊標對象 cursor cursor = db.cursor() # SQL 更新語句 sql = "UPDATE ip_table SET status = 1 WHERE ipaddress = '10.1.80.62'" try: # 執行SQL語句 cursor.execute(sql) # 提交到數據庫執行 db.commit() except: # 發生錯誤時回滾 db.rollback() # 關閉數據庫鏈接 db.close()
Python查詢Mysql使用 fetchone() 方法獲取單條數據, 使用fetchall() 方法獲取多條數據。 fetchone(): 該方法獲取下一個查詢結果集。結果集是一個對象 fetchall(): 接收所有的返回結果行 rowcount: 這是一個只讀屬性,並返回執行execute()方法後影響的行數。