亚洲免费在线-亚洲免费在线播放-亚洲免费在线观看-亚洲免费在线观看视频-亚洲免费在线看-亚洲免费在线视频

使用python連接mysql數(shù)據(jù)庫(kù)之pymysql模塊的使用

系統(tǒng) 1769 0

安裝pymysql

pip install pymysql

2|0使用pymysql

2|1使用數(shù)據(jù)查詢(xún)語(yǔ)句

查詢(xún)一條數(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語(yǔ)句
c.execute("select * from student")
# 查詢(xún)一行數(shù)據(jù)
result = c.fetchone()
print(result)
# 關(guān)閉游標(biāo)
c.close()
# 關(guān)閉數(shù)據(jù)庫(kù)連接
conn.close()
"""
(1, '張三', 18, b'\x01')
"""
          

查詢(xún)多條數(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語(yǔ)句
c.execute("select * from student")
# 查詢(xún)多行數(shù)據(jù)
result = c.fetchall()
for item in result:
  print(item)
# 關(guān)閉游標(biāo)
c.close()
# 關(guān)閉數(shù)據(jù)庫(kù)連接
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è)置為字典類(lèi)型
c = conn.cursor(cursors.DictCursor)
# 執(zhí)行sql語(yǔ)句
c.execute("select * from student")
# 查詢(xún)多行數(shù)據(jù)
result = c.fetchall()
for item in result:
  print(item)
# 關(guān)閉游標(biāo)
c.close()
# 關(guān)閉數(shù)據(jù)庫(kù)連接
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ù)操作語(yǔ)句

執(zhí)行增加、刪除、更新語(yǔ)句的操作其實(shí)是一樣的。只寫(xiě)一個(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語(yǔ)句
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ù)庫(kù)連接
conn.close()
          

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

3|0編寫(xiě)數(shù)據(jù)庫(kù)連接類(lèi)

普通版

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("連接已打開(kāi)")
    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()
          

該類(lèi)封裝了fetchone、fetchall、execute,省去了數(shù)據(jù)庫(kù)連接的打開(kāi)和關(guān)閉和游標(biāo)的打開(kāi)和關(guān)閉。
下面的代碼是調(diào)用該類(lèi)的小示例:

            
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è)置為字典類(lèi)型
    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ù)庫(kù)并執(zhí)行
    self.conn.commit()
    # 關(guān)閉游標(biāo)
    self.cur.close()
    # 關(guān)閉數(shù)據(jù)庫(kù)連接
    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'}
"""

          

總結(jié)

以上所述是小編給大家介紹的使用python連接mysql數(shù)據(jù)庫(kù)之pymysql模塊的使用,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)歡迎給我留言,小編會(huì)及時(shí)回復(fù)大家的!


更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主

微信掃碼或搜索:z360901061

微信掃一掃加我為好友

QQ號(hào)聯(lián)系: 360901061

您的支持是博主寫(xiě)作最大的動(dòng)力,如果您喜歡我的文章,感覺(jué)我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。

【本文對(duì)您有幫助就好】

您的支持是博主寫(xiě)作最大的動(dòng)力,如果您喜歡我的文章,感覺(jué)我的文章對(duì)您有幫助,請(qǐng)用微信掃描上面二維碼支持博主2元、5元、10元、自定義金額等您想捐的金額吧,站長(zhǎng)會(huì)非常 感謝您的哦?。。?/p>

發(fā)表我的評(píng)論
最新評(píng)論 總共0條評(píng)論
主站蜘蛛池模板: 国产成人综合亚洲亚洲欧美 | 久久99热精品免费观看k影院 | 欧美精品v欧洲高清 | 亚洲一区二区三区高清视频 | 亚洲一区二区三区四区五区 | 99日精品欧美国产 | 亚洲999| 久草视频免费播放 | 久久视频这里只有精品35 | 99色婷婷| 女人18毛片a级18毛多水真多 | 在线观看精品视频一区二区三区 | 欧美国产在线观看 | 亚洲毛片免费观看 | 2345成人高清毛片 | 亚洲se主站 | 九九热免费视频 | 久久精品国产亚洲精品2020 | 国内国语一级毛片在线视频 | 欧美日韩视频在线 | www.黄网站 | 男女污污视频在线观看 | 日韩中文字幕视频在线观看 | 大乳妇女bd视频在线观看 | 性欧美4k高清精品 | 福利在线免费视频 | 日韩中文精品亚洲第三区 | 亚洲四虎 | 天天干天天做 | 99热这里只有精品免费 | 看片久久 | 97在线免费观看视频 | 四虎影视永久 | 免费a级毛片大学生免费观看 | 久久久久久999 | 色资源站| 成人午夜影视全部免费看 | 91精品全国免费观看 | 一级特黄a视频 | 日本激情一区二区三区 | 欧美啪啪毛片一区二区 |