本篇文章給大家分享的是有關(guān)怎么在python中使用pymysql模塊連接mysql數(shù)據(jù)庫,小編覺得挺實(shí)用的,因此分享給大家學(xué)習(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ù)時(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'}
"""以上就是怎么在python中使用pymysql模塊連接mysql數(shù)據(jù)庫,小編相信有部分知識點(diǎn)可能是我們?nèi)粘9ぷ鲿?huì)見到或用到的。希望你能通過這篇文章學(xué)到更多知識。更多詳情敬請關(guān)注創(chuàng)新互聯(lián)成都網(wǎng)站設(shè)計(jì)公司行業(yè)資訊頻道。
另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務(wù)器15元起步,三天無理由+7*72小時(shí)售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務(wù)可用性高、性價(jià)比高”等特點(diǎn)與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場景需求。
分享標(biāo)題:怎么在python中使用pymysql模塊連接mysql數(shù)據(jù)庫-創(chuàng)新互聯(lián)
文章出自:http://www.chinadenli.net/article10/dcphgo.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供做網(wǎng)站、虛擬主機(jī)、商城網(wǎng)站、電子商務(wù)、云服務(wù)器、網(wǎng)站排名
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容