python操作mysql


1.  PyMySQL連接數據庫操作

1. 安裝 PyMySQL

什么是 PyMySQL?
PyMySQL 是在 Python3.x 版本中用於連接 MySQL 服務器的一個庫,Python2中則使用mysqldb。
PyMySQL 遵循 Python 數據庫 API v2.0 規范,並包含了 pure-Python MySQL 客戶端庫。

安裝PyMySQL

C:\Users\liqiang>e:

E:\>cd E:\pythonWorkSpace\FirstProject\venv\Scripts

E:\pythonWorkSpace\FirstProject\venv\Scripts>pip3 install PyMySQL

 

2. 進行數據庫連接

 1. 連接數據庫插卡可能版本

#!/usr/bin/python3

import pymysql

# 打開數據庫連接
db = pymysql.connect("localhost", "root", "123456", "pycraw")

# 使用 cursor() 方法創建一個游標對象 cursor
cursor = db.cursor()

# 使用 execute()  方法執行 SQL 查詢
cursor.execute("SELECT VERSION()")

# 使用 fetchone() 方法獲取單條數據.
data = cursor.fetchone()

print("Database version : %s " % data)

# 關閉數據庫連接
db.close()

結果:

Database version : 5.7.10-log 

 

2.數據庫進行插入操作

#!/usr/bin/python3

import pymysql

# 打開數據庫連接
db = pymysql.connect("localhost", "root", "123456", "pycraw")

# 使用cursor()方法獲取操作游標
cursor = db.cursor()

# SQL 插入語句
sql = "INSERT INTO user" \
      "(id, name ) \
       VALUES (%s, '%s')" % \
      (3, 'Mac')
try:
    # 執行sql語句
    cursor.execute(sql)
    # 執行sql語句
    db.commit()
except:
    # 發生錯誤時回滾
    db.rollback()

# 關閉數據庫連接
db.close()

 

 

3.  數據庫查詢操作

Python查詢Mysql使用 fetchone() 方法獲取單條數據, 使用fetchall() 方法獲取多條數據。
fetchone(): 該方法獲取下一個查詢結果集。結果集是一個對象。fetchone()函數它的返回值是單個的元組,也就是一行記錄,如果沒有結果,那就會返回null。
fetchall(): 接收全部的返回結果行。fetchall()函數,它的返回值是多個元組,即返回多個行記錄,如果沒有結果,返回的是()。
rowcount: 這是一個只讀屬性,並返回執行execute()方法后影響的行數。

 

(1)查詢ID等於1的數據

#!/usr/bin/python3

import pymysql

# 打開數據庫連接
db = pymysql.connect("localhost", "root", "123456", "pycraw")

# 使用cursor()方法獲取操作游標
cursor = db.cursor()

# SQL 查詢語句
sql = "SELECT * FROM user \
       WHERE id = %s" % (1)
try:
    # 執行SQL語句
    cursor.execute(sql)
    # 獲取所有記錄列表
    results = cursor.fetchone()
    # 打印結果
    print("id=%s,name=%s" % \
          (results[0], results[1]))
except:
    print("Error: unable to fetch data")

# 關閉數據庫連接
db.close()

結果:

id=1,name=zhangsan

 

(2)查詢ID大於1的數據

#!/usr/bin/python3

import pymysql

# 打開數據庫連接
db = pymysql.connect("localhost", "root", "123456", "pycraw")

# 使用cursor()方法獲取操作游標
cursor = db.cursor()

# SQL 查詢語句
sql = "SELECT * FROM user \
       WHERE id > %s" % (1)
try:
    # 執行SQL語句
    cursor.execute(sql)
    # 獲取所有記錄列表
    results = cursor.fetchall()
    for row in results:
        id = row[0]
        name = row[1]
        # 打印結果
        print("id=%s,name=%s" % \
              (id, name))

    total = cursor.rowcount
    print("總數: %s" % \
          (total))
except:
    print("Error: unable to fetch data")

# 關閉數據庫連接
db.close()

結果:

id=2,name=lisi
id=3,name=Mac

 

4. 執行修改操作:

#!/usr/bin/python3

import pymysql

# 打開數據庫連接
db = pymysql.connect("localhost", "root", "123456", "pycraw")

# 使用cursor()方法獲取操作游標
cursor = db.cursor()

# SQL 查詢語句
sql = "UPDATE user SET name = '%s' WHERE id = %s" % ('wangwu', 3)

try:
    # 執行SQL語句
    cursor.execute(sql)
    # 提交到數據庫執行
    db.commit()
except:
    # 發生錯誤時回滾
    db.rollback()

# 關閉數據庫連接
db.close()

 

5.刪除操作

#!/usr/bin/python3

import pymysql

# 打開數據庫連接
db = pymysql.connect("localhost", "root", "123456", "pycraw")

# 使用cursor()方法獲取操作游標
cursor = db.cursor()

# SQL 查詢語句
sql = "delete from  user WHERE id = %s" % ( 3)

try:
    # 執行SQL語句
    cursor.execute(sql)
    # 提交到數據庫執行
    db.commit()
except:
    # 發生錯誤時回滾
    db.rollback()

# 關閉數據庫連接
db.close()

 

補充:PyMySQL查詢數據庫並映射為dict類型數據:

#!/usr/bin/python3

import pymysql

# 打開數據庫連接
db = pymysql.connect("localhost", "root", "123456", "pycraw")

# 使用cursor()方法獲取操作游標
cursor = db.cursor(cursor = pymysql.cursors.DictCursor)

# SQL 查詢語句
sql = "SELECT * FROM user"

try:
    # 執行SQL語句
    cursor.execute(sql)
    # 獲取所有記錄列表
    results = cursor.fetchall()
    for result in results:
        # 打印結果
        print("result: %s" % (result))

except:
    print("Error: unable to fetch data")

# 關閉數據庫連接
db.close()

結果:

result: {'id': 1, 'name': 'zs', 'userName': 'zhangsan'}
result: {'id': 2, 'name': 'li', 'userName': 'lisi'}
result: {'id': 3, 'name': 'ww', 'userName': 'wangwu'}

 

2.  Python MySQL - mysql-connector 驅動

 mysql-connector 是 MySQL 官方提供的驅動器。我們可以使用 pip 命令來安裝 mysql-connector

python -m pip install mysql-connector

 

第一種: 檢測是否安裝成功:

import mysql.connector

執行以上代碼,如果沒有產生錯誤,表明安裝成功。

 

第二種驗證方式:查看模塊 (pip list 可以查看python安裝的模塊)

C:\Users\Administrator>pip list | findstr mysql
mysql-connector                    2.2.9

 

 

1.連接數據庫查看版本:

import mysql.connector

# 打開數據庫連接
db = mysql.connector.connect(
  host="localhost",       # 數據庫主機地址
  user="root",    # 數據庫用戶名
  passwd="123456"   # 數據庫密碼
)

# 使用 cursor() 方法創建一個游標對象 cursor
cursor = db.cursor()

# 使用 execute()  方法執行 SQL 查詢
cursor.execute("SELECT VERSION()")

# 使用 fetchone() 方法獲取單條數據.
data = cursor.fetchone()

print("Database version : %s " % data)

# 關閉數據庫連接
db.close()

結果:

Database version : 5.7.10-log

 

2. 連接到mysql指定的庫:

import mysql.connector

# 打開數據庫連接
db = mysql.connector.connect(
  host="localhost",       # 數據庫主機地址
  user="root",    # 數據庫用戶名
  passwd="123456",   # 數據庫密碼
  database="Exam9"    # 鏈接指定的庫,庫不存在會報錯
)

# 使用 cursor() 方法創建一個游標對象 cursor
cursor = db.cursor()

# 使用 execute()  方法執行 SQL 查詢
cursor.execute("SELECT VERSION()")

# 使用 fetchone() 方法獲取單條數據.
data = cursor.fetchone()

print("Database version : %s " % data)

# 關閉數據庫連接
db.close()

 

補充:手動安裝模塊pymysql

  模塊是一個包含所有你定義的函數和變量的文件,其后綴名是.py。模塊可以被別的程序引入,以使用該模塊中的函數等功能。這也是使用 python 標准庫的方法。(模塊類似於Java的class文件)

(1)到git上下載對應模塊: (一般模塊都能找到)

https://github.com/PyMySQL/PyMySQL

(2)解壓之后,進入到目錄下面 會有setup.py

(3) 進行安裝:

Administrator@MicroWin10-1535 MINGW64 ~/Desktop/pytest/新建文件夾/新建文件夾/PyMySQL-0.9.3
$ pip setup.py install

(4)測試: 引入模塊不報錯即安裝成功

import pymysql

 

補充:一個例子,python讀取數據庫,並讀取url、method、param去訪問請求,最后將結果記錄輸出到html中:

#!/usr/bin/python3
import pymysql
from urllib import request
import urllib.parse
import chardet
import json

# 訪問請求的方法
def requestUrl(result):
    url = str(result['url']);
    method = str(result['method']);
    data = str(result['param']);
    if url is None or method is None:
        return;
    
    if data is not None:
        data = str(data);
        data = data.replace("form=" , ""); # 去掉form=
        #數組參數處理
        if data.startswith('[') and data.endswith(']'):
            datas = json.loads(data);
            if len(datas) > 0:
                data = json.dumps(datas[0])
            else :
                data = '{"time": 1}';
        elif "{}" == data or "" == data:
            data = '{"time": 1}';
    else:
        data = '{"time": 1}';
    try:
        # POST請求
        if 'POST' in method:
            # 將序列化后的字符串轉換成二進制數據,因為post請求攜帶的是二進制參數
            last_data = bytes(data, encoding='utf-8');
            response = urllib.request.urlopen(url, data=last_data);
            responseResult = response.read().decode('utf-8')
            result['responseResult'] = responseResult
        else:
            data_string=urllib.parse.urlencode(data);
            new_url = url + "?" + data_string;
            response=urllib.request.urlopen(new_url)
            responseResult = response.read().decode('utf-8')
            result['responseResult'] = responseResult
    except Exception as e:
        result['responseResult'] = "error,原因: " + str(e)
        
        
# 輸出爬取到的數據到本地磁盤中
def out_html(datas):
    if datas is None:
        return;
        
    file = open('D:\\out.html', 'w', encoding='utf-8')
    file.write("<html>")
    file.write(r'''
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    ''');
    file.write("<head>")
    file.write("<title>爬取結果</title>")
    # 設置表格顯示邊框
    file.write(r'''
    <style>
     table{width:100%;table-layout: fixed;word-break: break-all; word-wrap: break-word;}
     table td{border:1px solid black;width:300px}
    </style>
    ''')
    file.write("</head>")
    file.write("<body>")
    file.write("<table cellpadding='0' cellspacing='0'>")
    # 遍歷datas填充到表格中
    for data in datas:
        file.write("<tr>")
        file.write("<td>%s</td>" % data['interfaceName'])
        file.write('<td><a href='+str(data['url'])+'>'+str(data['url'])+'</a></td>')
        file.write("<td>%s</td>" % data['method'])
        file.write("<td>%s</td>" % data['param'])
        file.write("<td>%s</td>" % data['responseResult'])
        file.write("</tr>")
    file.write("</table>")
    file.write("</body>")
    file.write("</html>")

    
#主函數用法
if __name__ == '__main__':    
    # 打開數據庫連接
    db = pymysql.connect("localhost", "root", "123456", "pycraw")
    # 使用cursor()方法獲取操作游標
    cursor = db.cursor(cursor = pymysql.cursors.DictCursor)
    # SQL 查詢語句
    sql = "SELECT * FROM interface ";

    try:
        # 執行SQL語句
        cursor.execute(sql)
        # 獲取所有記錄列表
        results = cursor.fetchall()

        for result in results:
            requestUrl(result);
            
        out_html(results);
        print("處理完成")
    except Exception as e:
        print(e);

    # 關閉數據庫連接
    db.close()

結果:

 


免責聲明!

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



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