亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

關(guān)于pymysql模塊的使用以及代碼詳解

 更新時(shí)間:2019年09月01日 14:06:32   作者:三國小夢  
在本篇文章里小編給大家整理的是關(guān)于關(guān)于pymysql模塊的使用以及代碼詳解,有興趣的朋友們學(xué)習(xí)下。

pymysql模塊的使用

查詢一條數(shù)據(jù)fetchone()

from pymysql import *

conn = connect(
  host='127.0.0.1',
  port=3306, user='root',
  password='123456',
  database='itcast',
  charset='utf8')

# 創(chuàng)建游標(biāo)
c = conn.cursor()
# 執(zhí)行sql語句
c.execute("select * from student")
# 查詢一行數(shù)據(jù)
result = c.fetchone()
print(result)
# 關(guān)閉游標(biāo)
c.close()
# 關(guān)閉數(shù)據(jù)庫連接
conn.close()
"""
(1, '張三', 18, b'\x01')
"""

查詢多條數(shù)據(jù)fetchall()

from pymysql import *

conn = connect(
  host='127.0.0.1',
  port=3306, user='root',
  password='123456',
  database='itcast',
  charset='utf8')

# 創(chuàng)建游標(biāo)
c = conn.cursor()
# 執(zhí)行sql語句
c.execute("select * from student")
# 查詢多行數(shù)據(jù)
result = c.fetchall()
for item in result:
  print(item)
# 關(guān)閉游標(biāo)
c.close()
# 關(guān)閉數(shù)據(jù)庫連接
conn.close()
"""
(1, '張三', 18, b'\x01')
(2, '李四', 19, b'\x00')
(3, '王五', 20, b'\x01')
"""

更改游標(biāo)的默認(rèn)設(shè)置,返回值為字典

from pymysql import *

conn = connect(
  host='127.0.0.1',
  port=3306, user='root',
  password='123456',
  database='itcast',
  charset='utf8')

# 創(chuàng)建游標(biāo),操作設(shè)置為字典類型
c = conn.cursor(cursors.DictCursor)
# 執(zhí)行sql語句
c.execute("select * from student")
# 查詢多行數(shù)據(jù)
result = c.fetchall()
for item in result:
  print(item)
# 關(guān)閉游標(biāo)
c.close()
# 關(guān)閉數(shù)據(jù)庫連接
conn.close()
"""
{'id': 1, 'name': '張三', 'age': 18, 'sex': b'\x01'}
{'id': 2, 'name': '李四', 'age': 19, 'sex': b'\x00'}
{'id': 3, 'name': '王五', 'age': 20, 'sex': b'\x01'}
"""

返回一條數(shù)據(jù)時(shí)也是一樣的。返回字典或者時(shí)元組看個(gè)人需要。

2|2使用數(shù)據(jù)操作語句

執(zhí)行增加、刪除、更新語句的操作其實(shí)是一樣的。只寫一個(gè)作為示范。

from pymysql import *

conn = connect(
  host='127.0.0.1',
  port=3306, user='root',
  password='123456',
  database='itcast',
  charset='utf8')

# 創(chuàng)建游標(biāo)
c = conn.cursor()
# 執(zhí)行sql語句
c.execute("insert into student(name,age,sex) values (%s,%s,%s)",("小二",28,1))
# 提交事務(wù)
conn.commit()
# 關(guān)閉游標(biāo)
c.close()
# 關(guān)閉數(shù)據(jù)庫連接
conn.close()

和查詢語句不同的是必須使用commit()提交事務(wù),否則操作就是無效的。

3|0編寫數(shù)據(jù)庫連接類

普通版

MysqlHelper.py

from pymysql import connect,cursors

class MysqlHelper:
  def __init__(self,
         host="127.0.0.1",
         user="root",
         password="123456",
         database="itcast",
         charset='utf8',
         port=3306):
    self.host = host
    self.port = port
    self.user = user
    self.password = password
    self.database = database
    self.charset = charset
    self._conn = None
    self._cursor = None

  def _open(self):
    # print("連接已打開")
    self._conn = connect(host=self.host,
               port=self.port,
               user=self.user,
               password=self.password,
               database=self.database,
               charset=self.charset)
    self._cursor = self._conn.cursor(cursors.DictCursor)

  def _close(self):
    # print("連接已關(guān)閉")
    self._cursor.close()
    self._conn.close()

  def one(self, sql, params=None):
    result: tuple = None
    try:
      self._open()
      self._cursor.execute(sql, params)
      result = self._cursor.fetchone()
    except Exception as e:
      print(e)
    finally:
      self._close()
    return result

  def all(self, sql, params=None):
    result: tuple = None
    try:
      self._open()
      self._cursor.execute(sql, params)
      result = self._cursor.fetchall()
    except Exception as e:
      print(e)
    finally:
      self._close()
    return result

  def exe(self, sql, params=None):
    try:
      self._open()
      self._cursor.execute(sql, params)
      self._conn.commit()
    except Exception as e:
      print(e)
    finally:
      self._close()

該類封裝了fetchone、fetchall、execute,省去了數(shù)據(jù)庫連接的打開和關(guān)閉和游標(biāo)的打開和關(guān)閉。

下面的代碼是調(diào)用該類的小示例:

from MysqlHelper import *

mysqlhelper = MysqlHelper()
ret = mysqlhelper.all("select * from student")
for item in ret:
  print(item)
"""
{'id': 1, 'name': '張三', 'age': 18, 'sex': b'\x01'}
{'id': 2, 'name': '李四', 'age': 19, 'sex': b'\x00'}
{'id': 3, 'name': '王五', 'age': 20, 'sex': b'\x01'}
{'id': 5, 'name': '小二', 'age': 28, 'sex': b'\x01'}
{'id': 6, 'name': '娃哈哈', 'age': 28, 'sex': b'\x01'}
{'id': 7, 'name': '娃哈哈', 'age': 28, 'sex': b'\x01'}
"""

上下文管理器版

mysql_with.py

from pymysql import connect, cursors

class DB:
  def __init__(self,
         host='localhost',
         port=3306,
         db='itcast',
         user='root',
         passwd='123456',
         charset='utf8'):
    # 建立連接
    self.conn = connect(
      host=host,
      port=port,
      db=db,
      user=user,
      passwd=passwd,
      charset=charset)
    # 創(chuàng)建游標(biāo),操作設(shè)置為字典類型
    self.cur = self.conn.cursor(cursor=cursors.DictCursor)

  def __enter__(self):
    # 返回游標(biāo)
    return self.cur

  def __exit__(self, exc_type, exc_val, exc_tb):
    # 提交數(shù)據(jù)庫并執(zhí)行
    self.conn.commit()
    # 關(guān)閉游標(biāo)
    self.cur.close()
    # 關(guān)閉數(shù)據(jù)庫連接
    self.conn.close()

如何使用:

from mysql_with import DB

with DB() as db:
  db.execute("select * from student")
  ret = db.fetchone()
  print(ret)

"""
{'id': 1, 'name': '張三', 'age': 18, 'sex': b'\x01'}
"""

以上就是本次介紹的全部知識點(diǎn)內(nèi)容,感謝大家的閱讀和對腳本之家的支持。

相關(guān)文章

  • python 對多個(gè)csv文件分別進(jìn)行處理的方法

    python 對多個(gè)csv文件分別進(jìn)行處理的方法

    今天小編就為大家分享一篇python 對多個(gè)csv文件分別進(jìn)行處理的方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-01-01
  • 分享給Python新手們的幾道簡單練習(xí)題

    分享給Python新手們的幾道簡單練習(xí)題

    這篇文章主要給學(xué)習(xí)Python的新手們分享了幾道簡單練習(xí)題,文中給出了詳細(xì)的示例代碼供大家學(xué)習(xí)參考,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。
    2017-09-09
  • 如何用scheduler實(shí)現(xiàn)learning-rate學(xué)習(xí)率動(dòng)態(tài)變化

    如何用scheduler實(shí)現(xiàn)learning-rate學(xué)習(xí)率動(dòng)態(tài)變化

    這篇文章主要介紹了如何用scheduler實(shí)現(xiàn)learning-rate學(xué)習(xí)率動(dòng)態(tài)變化問題,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-09-09
  • Python?sns.distplot()方法的使用方法

    Python?sns.distplot()方法的使用方法

    機(jī)器學(xué)習(xí)中經(jīng)常會(huì)用到圖形進(jìn)行可視化,如在網(wǎng)格搜索(GridSearch)后對特征的重要性進(jìn)行排序時(shí),用到sns.barplot()函數(shù)按照重要程度輸出特征,這篇文章主要給大家介紹了關(guān)于Python?sns.distplot()方法的使用方法,需要的朋友可以參考下
    2022-03-03
  • Django自定義權(quán)限及用戶分組

    Django自定義權(quán)限及用戶分組

    這篇文章主要為大家介紹了Django登錄權(quán)限及分組模板使用權(quán)限,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-06-06
  • Python aiohttp百萬并發(fā)極限測試實(shí)例分析

    Python aiohttp百萬并發(fā)極限測試實(shí)例分析

    這篇文章主要介紹了Python aiohttp百萬并發(fā)極限測試,結(jié)合實(shí)例形式分析了Python異步編程基于aiohttp客戶端高并發(fā)請求的相關(guān)操作技巧與使用注意事項(xiàng),需要的朋友可以參考下
    2019-10-10
  • Python使用time模塊實(shí)現(xiàn)指定時(shí)間觸發(fā)器示例

    Python使用time模塊實(shí)現(xiàn)指定時(shí)間觸發(fā)器示例

    這篇文章主要介紹了Python使用time模塊實(shí)現(xiàn)指定時(shí)間觸發(fā)器,結(jié)合實(shí)例形式分析了Python時(shí)間相關(guān)模塊與方法使用技巧,需要的朋友可以參考下
    2017-05-05
  • Python3+PyInstall+Sciter解決報(bào)錯(cuò)缺少dll、html等文件問題

    Python3+PyInstall+Sciter解決報(bào)錯(cuò)缺少dll、html等文件問題

    這篇文章主要介紹了Python3+PyInstall+Sciter解決報(bào)錯(cuò)缺少dll、html等文件問題,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2019-07-07
  • Python使用pydub庫對mp3與wav格式進(jìn)行互轉(zhuǎn)的方法

    Python使用pydub庫對mp3與wav格式進(jìn)行互轉(zhuǎn)的方法

    今天小編就為大家分享一篇Python使用pydub庫對mp3與wav格式進(jìn)行互轉(zhuǎn)的方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-01-01
  • python arcpy練習(xí)之面要素重疊拓?fù)錂z查

    python arcpy練習(xí)之面要素重疊拓?fù)錂z查

    今天小編就為大家分享一篇Python ArcPy的面要素重疊拓?fù)錂z查,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2021-09-09

最新評論