新聞中心
下文給大家?guī)黻P(guān)于python3連接MySQL實(shí)際操作,感興趣的話就一起來看看python3連接mysql實(shí)際操作這篇文章吧,相信看完對(duì)大家多少有點(diǎn)幫助吧。
調(diào)兵山網(wǎng)站建設(shè)公司創(chuàng)新互聯(lián),調(diào)兵山網(wǎng)站設(shè)計(jì)制作,有大型網(wǎng)站制作公司豐富經(jīng)驗(yàn)。已為調(diào)兵山上1000+提供企業(yè)網(wǎng)站建設(shè)服務(wù)。企業(yè)網(wǎng)站搭建\成都外貿(mào)網(wǎng)站制作要多少錢,請(qǐng)找那個(gè)售后服務(wù)好的調(diào)兵山做網(wǎng)站的公司定做!
python3 連接mysql數(shù)據(jù)庫(kù),執(zhí)行操作。
環(huán)境:
os: windows 2008
python: python 3.5.3
之前用過python3連接sqlite3數(shù)據(jù)庫(kù),只是作為單機(jī)數(shù)據(jù)庫(kù)使用,但后來提供web服務(wù)時(shí),sqlite3數(shù)據(jù)庫(kù)支持的不夠好,轉(zhuǎn)而使用mysql數(shù)據(jù)庫(kù)。
python3連接數(shù)據(jù)庫(kù)使用pymysql模塊。
下面總結(jié)一下,寫成類方便使用:
class ConMysql: def __init__(self, host, username, password, database): self._database = database self._host = host self._user = username self._passwd = password def connect(self): """連接數(shù)據(jù)庫(kù),執(zhí)行SQL語(yǔ)句,返回元組""" #連接數(shù)據(jù)庫(kù) try: self._db = pymysql.connect(self._host, self._user, self._passwd, self._database) except (ConnectionRefusedError, pymysql.err.OperationalError, pymysql.err.InternalError) as _con_err: return False, _con_err else: return True, 'OK' def get_data(self, _sql_str, s='r'): # 查詢 _cur = self._db.cursor() try: _cur.execute(_sql_str) except (pymysql.err.InternalError, pymysql.err.OperationalError, pymysql.err.ProgrammingError) as _sql_err: _cur.close() return False, _sql_err if s == 'r' _cur.close() _array = _cur.fetchall() return True, _array else: _cur.close() self._db.commit() return True, 'OK' def edit_data(self, _sql_str): # 修改 return self.get_data(_sql_str, 'w') def __del__(self): self._db.close()
這里讀數(shù)據(jù)庫(kù)沒有問題,在插入或修改時(shí)會(huì)報(bào)錯(cuò),因?yàn)榫幋a的問題,pymysql默認(rèn)會(huì)把所以的sql字符串編譯成byte,為了避免錯(cuò)誤可以添加兩個(gè)參數(shù),use_unicode=True, charset='utf8'。其實(shí)在實(shí)例化時(shí)還有很多可選參數(shù),詳細(xì)的可以查看文檔或你已經(jīng)安裝的源代碼connection。
看了以上關(guān)于python3連接mysql實(shí)際操作詳細(xì)內(nèi)容,是否有所收獲。如果想要了解更多相關(guān),可以繼續(xù)關(guān)注我們的行業(yè)資訊板塊。
新聞標(biāo)題:python3連接mysql實(shí)際操作
文章轉(zhuǎn)載:http://fisionsoft.com.cn/article/giepdo.html