命令安裝:python
sudo apt-get install python-mysql
或者mysql
pip install pymysql
二、使用在pyCharm中安裝PyMySQL模塊sql
conn=connect(參數列表)
cursor1=conn.cursor()
一、咱們建立MySQLManager.py模塊,對Mysql的基本操做封裝數據庫
# coding=utf-8; # 導入模塊pymysql模塊 import pymysql # 封裝MySQL數據庫管理類 class MySQL_Manager(object): # 初始化方法 def __init__(self,host,port,database,user,password,charset='utf8'): # 配置鏈接MySQL數據庫的基本信息 self.host = host self.port = port self.database = database self.user = user self.password = password self.charset = charset # 使用python3連接MySQL數據庫 def connect(self): # 連接 self.connect = pymysql.connect(host = self.host, port = self.port, database = self.database, user = self.user, password = self.password,charset = self.charset) # 獲得一個能夠執行SQL語句的光標對象 self.cursor = self.connect.cursor() # 操做完畢後關閉 def close(self): # 關閉執行語句 self.cursor.close() # 關閉鏈接 self.connect.close() # 建立表操做 def create_table(self,sql,params=()): # 先鏈接 self.connect() # 執行建立語句 self.cursor.execute(sql,params) # 關閉鏈接 self.close() # 查詢一條數據 def select_one(self,sql,params=()): result = None try: self.connect() self.cursor.execute(sql,params) result = self.cursor.fetchone() self.close() except Exception as e: print(e) return result # 查詢所有數據 def select_all(self,sql,params=()): list=() try: self.connect() self.cursor.execute(sql,params) list = self.cursor.fetchall() self.close() except Exception as e: print(e) return list # 插入 def insert(self, sql, params=()): return self.__edit(sql, params) # 修改 def update(self, sql, params=()): return self.__edit(sql, params) # 刪除 def delete(self, sql, params=()): return self.__edit(sql, params) # 插入、修改、刪除其實同樣的,只是sql代碼不一樣,可是爲了代碼的閱讀性更高,仍是分開寫 def __edit(self, sql, params): count = 0 try: self.connect() count = self.cursor.execute(sql, params) self.connect.commit() self.close() except Exception as e: print(e) return count
2.建立testMySQL.py模塊對咱們建立的MySQLManager.py模塊測試測試
# coding = utf-8 from MySQLManager import * mysql_manager = MySQL_Manager("192.168.100.114",3306,"Hero","root","123456") # 建立表 create_sql = "create table hero(id int auto_increment primary key,name varchar(20) not null unique,skill varchar(20) not null) engine=innodb default charset=utf8;" mysql_manager.create_table(create_sql) # 添加數據 insert_sql = "insert into hero(id,name,skill) values(1,'李白','青蓮劍歌');" mysql_manager.insert(insert_sql) # 查詢語句 select_sql = "select * from hero;" list = mysql_manager.select_all(select_sql) print(list) # 修改 update_sql = "update hero set name='韓信' where id=1;" mysql_manager.update(update_sql) # 刪除語句 delete_sql = "delete from hero where id=1;" mysql_manager.delete(delete_sql)
說明:fetch