python3連接mysql
- 2020 年 1 月 3 日
- 筆記
python3 連接mysql資料庫,執行操作。
環境: os: windows 2008 python: python 3.5.3
之前用過python3連接sqlite3資料庫,只是作為單機資料庫使用,但後來提供web服務時,sqlite3資料庫支援的不夠好,轉而使用mysql資料庫。
python3連接資料庫使用pymysql模組。
下面總結一下,寫成類方便使用:
class ConMysql: def __init__(self, host, username, password, database): self._database = database self._host = host self._user = username self._passwd = password def connect(self): """連接資料庫,執行SQL語句,返回元組""" #連接資料庫 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()
這裡讀資料庫沒有問題,在插入或修改時會報錯,因為編碼的問題,pymysql默認會把所以的sql字元串編譯成byte,為了避免錯誤可以添加兩個參數,use_unicode=True, charset='utf8'。其實在實例化時還有很多可選參數,詳細的可以查看文檔或你已經安裝的源程式碼connection。