這篇文章主要介紹了python中操作mysql的方法,具有一定借鑒價(jià)值,需要的朋友可以參考下。希望大家閱讀完這篇文章后大有收獲。下面讓小編帶著大家一起了解一下。
mysql 使用
啟動(dòng)服務(wù)
sudo systemctl start mysql
pip3 install pymysql
python 操作數(shù)據(jù)庫:
import pymysql class MyDb(): def __init__(self, host, user, passwd, db): self.__db = pymysql.connect(host, user, passwd, db) self.__cursor = self.__db.cursor() # 增刪改-數(shù)據(jù)庫 def set(self, sql): try: self.__cursor.execute(sql) self.__db.commit() except Exception as e: self.__db.rollback() print('Execute Error: \n {e}') # 查-數(shù)據(jù)庫 def get(self, sql, fetchone=True): self.__cursor.execute(sql) try: if fetchone == True: data = self.__cursor.fetchone() else: data = self.__cursor.fetchall() except Exception as e: print('Execute Error: \n {e}') data = None finally: return data # 關(guān)閉數(shù)據(jù)庫 def close(self): self.__db.close()