python如何操作mysql
更新時間:2020年08月17日 11:18:54 作者:云雀叫了一整天
這篇文章主要介紹了python如何操作MySQL,幫助大家更好的理解和學(xué)習(xí)python,感興趣的朋友可以了解下
mysql 使用
啟動服務(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()
- 調(diào)用
def example(): ## 實例化數(shù)據(jù)庫 ### 類參數(shù):host、user、passwd、db db = MyDb('localhost', 'root', 'zuoy123', 'test') ## 查看版本 get_version_sql = 'SELECT VERSION()' version = db.get(get_version_sql) print(f'Database Version: {version}') ## 刪除表 delete_table_sql = 'DROP TABLE IF EXISTS employee' db.set(delete_table_sql) ## 新建表 new_table_sql = 'CREATE TABLE IF NOT EXISTS employee( \ id INT NOT NULL PRIMARY KEY, \ name CHAR(21) NOT NULL, \ age DOUBLE DEFAULT 18)' db.set(new_table_sql) ## 查找表 get_table_sql = 'SHOW TABLES' data = db.get(get_table_sql) if data: print(data) ## 關(guān)閉數(shù)據(jù)庫 db.close() if __name__ == '__main__': example()
常用sql
DROP TABLE IF EXISTS employee; CREATE TABLE IF NOT EXISTS employee(id INT);
以上就是python操作 mysql的步驟的詳細(xì)內(nèi)容,更多關(guān)于python操作 mysql的資料請關(guān)注腳本之家其它相關(guān)文章!
您可能感興趣的文章:
- pymysql實現(xiàn)增刪改查的操作指南(python)
- Python基礎(chǔ)之操作MySQL數(shù)據(jù)庫
- python操作mysql、excel、pdf的示例
- python安裝mysql的依賴包mysql-python操作
- Python pymysql模塊安裝并操作過程解析
- 使用Python操作MySQL的小技巧
- Python連接mysql數(shù)據(jù)庫及簡單增刪改查操作示例代碼
- Python操作MySQL數(shù)據(jù)庫的示例代碼
- python3 使用openpyxl將mysql數(shù)據(jù)寫入xlsx的操作
- 教你怎么用Python操作MySql數(shù)據(jù)庫
相關(guān)文章
用Python將IP地址在整型和字符串之間輕松轉(zhuǎn)換
這篇文章主要給大家介紹了利用Python將IP在整型和字符串之間輕松轉(zhuǎn)換的相關(guān)資料,文中還跟大家分享了Python下利用正則表達(dá)式來匹配校驗一個字符串是否為ip地址的方法,需要的朋友可以參考借鑒,下面來一起看看吧。2017-03-03python肯德爾系數(shù)相關(guān)性數(shù)據(jù)分析示例
這篇文章主要為大家介紹了python肯德爾系數(shù)相關(guān)性數(shù)據(jù)分析示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-02-02使用paramiko遠(yuǎn)程執(zhí)行命令、下發(fā)文件的實例
下面小編就為大家?guī)硪黄褂胮aramiko遠(yuǎn)程執(zhí)行命令、下發(fā)文件的實例。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-10-10