国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python使用pymysql實現操作mysql

2019-11-25 16:34:02
字體:
來源:轉載
供稿:網友

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("請選擇操作");

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 博客| 彭水| 临安市| 吴桥县| 儋州市| 吉隆县| 阳新县| 石泉县| 通州区| 军事| 济阳县| 梨树县| 灯塔市| 惠水县| 赤水市| 玛曲县| 万源市| 南汇区| 台中县| 涿州市| 玉田县| 永宁县| 广丰县| 沈阳市| 宣城市| 康平县| 高雄市| 随州市| 嵊泗县| 中卫市| 田东县| 阆中市| 惠安县| 眉山市| 合川市| 乌鲁木齐县| 凤台县| 苗栗市| 临漳县| 特克斯县| 巩留县|