欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時間:2019年09月01日 11:56:06   作者:三國小夢  
這篇文章主要介紹了使用python連接mysql數(shù)據(jù)庫之pymysql模塊的使用,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下

安裝pymysql

pip install pymysql

2|0使用pymysql

2|1使用數(shù)據(jù)查詢語句

查詢一條數(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ù)時也是一樣的。返回字典或者時元組看個人需要。

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

執(zhí)行增加、刪除、更新語句的操作其實(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)
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'}
"""

總結(jié)

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

相關(guān)文章

  • MySQL學(xué)習(xí)第五天 MySQL數(shù)據(jù)庫基本操作

    MySQL學(xué)習(xí)第五天 MySQL數(shù)據(jù)庫基本操作

    MySQL學(xué)習(xí)第五天我們將針對MySQL數(shù)據(jù)庫進(jìn)行基本操作,創(chuàng)建、修改、刪除數(shù)據(jù)庫等一系列操作進(jìn)行學(xué)習(xí),感興趣的小伙伴們可以參考一下
    2016-05-05
  • 分享下mysql各個主要版本之間的差異

    分享下mysql各個主要版本之間的差異

    因?yàn)閙ysql的版本較多,而且又被oracle公司收購,所有很多朋友不是很清楚各個版本的區(qū)別,這里簡單介紹下,方便需要的朋友
    2013-06-06
  • 詳解mysql 組合查詢

    詳解mysql 組合查詢

    這篇文章主要介紹了詳解mysql 組合查詢的的相關(guān)資料,幫助大家更好的理解和使用MySQL數(shù)據(jù)庫,感興趣的朋友可以了解下
    2020-12-12
  • 用shell寫一個mysql數(shù)據(jù)備份腳本

    用shell寫一個mysql數(shù)據(jù)備份腳本

    本篇文章教給大家用shell寫一個mysql數(shù)據(jù)備份腳本,這是一個簡單備份MYSQL數(shù)據(jù)庫的方法,一起跟著學(xué)習(xí)下吧。
    2017-12-12
  • MySQL緩存的查詢和清除命令使用詳解

    MySQL緩存的查詢和清除命令使用詳解

    這篇文章主要介紹了MySQL緩存的查詢和清除命令使用詳解,對于一些不常改變數(shù)據(jù)且有大量相同sql查詢的表,查詢緩存會顯得比較有用一些,需要的朋友可以參考下
    2015-12-12
  • MySQL雙層游標(biāo)嵌套循環(huán)實(shí)現(xiàn)方法

    MySQL雙層游標(biāo)嵌套循環(huán)實(shí)現(xiàn)方法

    要實(shí)現(xiàn)逐行獲取數(shù)據(jù),需要用到MySQL中的游標(biāo),一個游標(biāo)相當(dāng)于一個for循環(huán),這里需要用到2個游標(biāo),如何在MySQL中實(shí)現(xiàn)游標(biāo)雙層循環(huán)呢,下面小編給大家分享MySQL雙層游標(biāo)嵌套循環(huán)方法,感興趣的朋友跟隨小編一起看看吧
    2024-05-05
  • win10 下安裝mysql服務(wù)器社區(qū)版本mysql 5.7.22 winx64的圖文教程

    win10 下安裝mysql服務(wù)器社區(qū)版本mysql 5.7.22 winx64的圖文教程

    這篇文章主要介紹了win10 下安裝mysql服務(wù)器社區(qū)版本mysql 5.7.22 winx64的圖文教程,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下
    2018-05-05
  • MySql8設(shè)置遠(yuǎn)程連接的實(shí)戰(zhàn)記錄

    MySql8設(shè)置遠(yuǎn)程連接的實(shí)戰(zhàn)記錄

    與SQL Server類似,MySQL在需要遠(yuǎn)程操縱其他電腦時,也需要對其做遠(yuǎn)程連接的相應(yīng)設(shè)置,下面這篇文章主要給大家介紹了關(guān)于MySql8設(shè)置遠(yuǎn)程連接的相關(guān)資料,文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考下
    2022-04-04
  • 一起來了解mysql數(shù)據(jù)庫

    一起來了解mysql數(shù)據(jù)庫

    大家好,本篇文章主要講的是一起來了解mysql數(shù)據(jù)庫,感興趣的同學(xué)趕快來看一看吧,對你有幫助的話記得收藏一下,方便下次瀏覽
    2021-12-12
  • mysql查詢條件not in 和 in的區(qū)別及原因說明

    mysql查詢條件not in 和 in的區(qū)別及原因說明

    這篇文章主要介紹了mysql查詢條件not in 和 in的區(qū)別及原因說明,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2021-01-01

最新評論