pymysql操做mysql

 

1、使用PyMySQL操做mysql數據庫

適用環境python

python版本 >=2.6或3.3
mysql版本>=4.1

安裝mysql

能夠使用pip安裝也能夠手動下載安裝。使用pip安裝,在命令行執行以下命令:git

pip install PyMySQL

手動安裝,請先下載。下載地址:https://github.com/PyMySQL/PyMySQL/tarball/pymysql-X.X。其中的X.X是版本。github

下載後解壓壓縮包。在命令行中進入解壓後的目錄,執行以下的指令:sql

python setup.py install

建議使用pip安裝數據庫

 

2、使用示例

鏈接數據庫以下:django

import pymysql.cursors

# Connect to the database
connection = pymysql.connect(host='127.0.0.1',
    port=3306,
    user='root',
    password='zhyea.com',
    db='employees',
    charset='utf8mb4',
    cursorclass=pymysql.cursors.DictCursor
)

也能夠使用字典進行鏈接參數的管理,我以爲這樣子更優雅一些fetch

import pymysql.cursors

config = {
    'host':'127.0.0.1',
    'port':3306,
    'user':'root',
    'db':'employees',
    'charset':'utf8mb4',
    'cursorclass':pymysql.cursors.DictCursor,
}

# Connect to the database
connection = pymysql.connect(**config)

 

插入數據:spa

執行sql語句前須要獲取cursor,由於配置默認自動提交,故在執行sql語句後須要主動commit,最後不要忘記關閉鏈接:命令行

from datetime import date, datetime, timedelta
import pymysql.cursors
 
# 鏈接配置信息
config = {
          'host':'127.0.0.1',
          'port':3306,
          'user':'root',
          'password':'zhyea.com',
          'db':'employees',
          'charset':'utf8mb4',
          'cursorclass':pymysql.cursors.DictCursor,
          }
# 建立鏈接
connection = pymysql.connect(**config)
 
# 獲取明天的時間
tomorrow = datetime.now().date() + timedelta(days=1)
 
# 執行sql語句
try:
    with connection.cursor() as cursor:
        # 執行sql語句,插入記錄
        sql = 'INSERT INTO employees (first_name, last_name, hire_date, gender, birth_date) VALUES (%s, %s, %s, %s, %s)'
        cursor.execute(sql, ('Robin''Zhyea', tomorrow, 'M', date(1989, 6, 14)));
    # 沒有設置默認自動提交,須要主動提交,以保存所執行的語句
    connection.commit()
 
finally:
    connection.close();

 

執行查詢

import datetime
import pymysql.cursors
 
#鏈接配置信息
config = {
          'host':'127.0.0.1',
          'port':3306,
          'user':'root',
          'password':'zhyea.com',
          'db':'employees',
          'charset':'utf8mb4',
          'cursorclass':pymysql.cursors.DictCursor,
          }
# 建立鏈接
connection = pymysql.connect(**config)
 
# 獲取僱傭日期
hire_start = datetime.date(1999, 1, 1)
hire_end = datetime.date(2016, 12, 31)
 
# 執行sql語句
try:
    with connection.cursor() as cursor:
        # 執行sql語句,進行查詢
        sql = 'SELECT first_name, last_name, hire_date FROM employees WHERE hire_date BETWEEN %s AND %s'
        cursor.execute(sql, (hire_start, hire_end))
        # 獲取查詢結果
        result = cursor.fetchone()
        print(result)
    # 沒有設置默認自動提交,須要主動提交,以保存所執行的語句
    connection.commit()
 
finally:
    connection.close();

這裏的查詢支取了一條查詢結果,查詢結果以字典的形式返回

從結果集中獲取指定數目的記錄,能夠使用fetchmany方法:

result = cursor.fetchmany(2)

不過不建議這樣使用,最好在sql語句中設置查詢的記錄總數。

獲取所有結果集能夠使用fetchall方法:

result = cursor.fetchall()

由於只有兩條記錄,因此上面提到的這兩種查詢方式查到的結果是同樣的:

[
 {'last_name''Vanderkelen''hire_date': datetime.date(2015, 8, 12), 'first_name''Geert'},
 {'last_name':'Zhyea''hire_date': datetime.date(2015, 8, 21), 'first_name''Robin'}
]

 

3、在django中使用

設置DATABASES和官方推薦使用的MySQLdb的設置沒什麼區別:

DATABASES = {
   'default': {
        'ENGINE''django.db.backends.mysql',
        'NAME''mytest',
        'USER''root',
        'PASSWORD''zhyea.com',
        'HOST''127.0.0.1',
        'PORT''3306',
    }
}

關鍵是這裏:咱們還須要在站點的__init__.py文件中添加以下的內容:

import pymysql
pymysql.install_as_MySQLdb()
相關文章
相關標籤/搜索