python使用pymysql實現操作mysql,pythonpymysql

來源:互聯網
上載者:User

python使用pymysql實現操作mysql,pythonpymysql

pymsql是Python中操作MySQL的模組,其使用方法和MySQLdb幾乎相同。但目前pymysql支援python3.x而後者不支援3.x版本。

適用環境

python版本 >=2.6或3.3

mysql版本>=4.1

安裝

可以使用pip安裝也可以手動下載安裝。

使用pip安裝,在命令列執行如下命令:

pip install PyMySQL

手動安裝,請先下載。:https://github.com/PyMySQL/PyMySQL/tarball/pymysql-X.X。

其中的X.X是版本(目前可以擷取的最新版本是0.6.6)。

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

python setup.py install

建議使用pip安裝。

使用樣本

串連資料庫如下:

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

也可以使用字典進行串連參數的管理,我覺得這樣子更優雅一些:

import pymysql.cursors config = {     'host':'127.0.0.1',     'port':3306,     'user':'root',     'password':'zhyea.com',     'db':'employees',     'charset':'utf8mb4',     'cursorclass':pymysql.cursors.DictCursor,     } # Connect to the databaseconnection = pymysql.connect(**config)

插入資料:

執行sql語句前需要擷取cursor,因為配置預設自動認可,故在執行sql語句後需要主動commit,最後不要忘記關閉串連:

from datetime import date, datetime, timedeltaimport 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 datetimeimport 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'}]

在django中使用

在django中使用是我找這個的最初目的。目前同時支援python3.4、django1.8的資料庫backend並不好找。這個是我目前找到的最好用的。

設定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()

最後給大家附上pymysql實現增刪改查的代碼,希望大家能夠喜歡

#!/usr/bin/python#coding:gbkimport pymysqlfrom builtins import int#將MysqlHelper的幾個函數寫出來def connDB():               #串連資料庫  conn=pymysql.connect(host="localhost",user="root",passwd="zx69728537",db="student");  cur=conn.cursor();  return (conn,cur);def exeUpdate(conn,cur,sql):        #更新或插入操作  sta=cur.execute(sql);  conn.commit();  return (sta);def exeDelete(conn,cur,IDs):        #刪除操作  sta=0;  for eachID in IDs.split(' '):    sta+=cur.execute("delete from students where Id=%d"%(int(eachID)));  conn.commit();  return (sta);    def exeQuery(cur,sql):           #尋找操作  cur.execute(sql);  return (cur);  def connClose(conn,cur):          #關閉串連,釋放資源  cur.close();  conn.close();result=True;print("請選擇以上四個操作:1、修改記錄,2、增加記錄,3、查詢記錄,4、刪除記錄.(按q為退出)");conn,cur=connDB();number=input();while(result):  if(number=='q'):    print("結束操作");    break;  elif(int(number)==1):    sql=input("請輸入更新語句:");    try:      exeUpdate(conn, cur, sql);      print("更新成功");    except Exception:      print("更新失敗");      raise;  elif(int(number)==2):      sql=input("請輸入新增語句:");      try:        exeUpdate(conn, cur, sql);        print("新增成功");      except Exception:        print("新增失敗");        raise;  elif(int(number)==3):    sql=input("請輸入查詢語句:");    try:      cur=exeQuery(cur, sql);      for item in cur:        print("Id="+str(item[0])+" name="+item[1]);    except Exception:      print("查詢出錯");      raise;  elif(int(number)==4):    Ids=input("請輸入Id,並用空格隔開");    try:      exeDelete(conn, cur, Ids);      print("刪除成功");    except Exception:      print("刪除失敗");      raise;  else:    print("非法輸入,將結束操作!");    result=False;    break;  print("請選擇以上四個操作:1、修改記錄,2、增加記錄,3、查詢記錄,4、刪除記錄.(按q為退出)");  number=input("請選擇操作");

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.