Python如何操作MySQL

安裝Mysql和Navicat for MySQL

mysql的安裝圖解https://jingyan.baidu.com/art… navicat for mysql破解可以看下這個文章https://www.cnblogs.com/da199…

Python鏈接Mysql的增刪改查

通過Python提供的pymysql模組實現對mysql資料庫的操作,這個地方注意python3.x使用的是pymysql,python2.x的話使用mysqldb模組 安裝pymysql模組:pip install PyMySQL

import pymysql    # 創建連接  conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123456', db='student')  # 創建游標  cursor = conn.cursor()    # 修改----執行SQL,並返回受影響行數  # effect_row = cursor.execute("update user set name=%s,pwd=%s where id=%s", ('aaa','bb', 1))    # 添加----執行SQL,並返回受影響行數  # cursor.execute("insert into user (name, pwd) values (%s,%s)", ("lidao","aaa"))  # 查詢----  cursor.execute("select * from user")  stus = cursor.fetchall()  for stu in stus:          print("id:%d; name: %s; pwd: %s; " %(stu[0], stu[1], stu[2]))    # 刪除---執行SQL,並返回受影響行數  cursor.execute("delete from user where id=%s", (2))    # 提交,不然無法保存新建或者修改的數據  conn.commit()  #如果不加這個就手動添加autocommit=True 自動提交  #db=pymysql.connect(host="127.0.0.1",port=3306,user="root",passwd="123456",db="school",charset="utf8",autocommit=True)        # 關閉游標  cursor.close()  # 關閉連接  conn.close()

自己封裝helper類

import pymysql    class dbhelper():      def __init__(self,host,port,user,passwd,db,charset="utf8"):          self.host=host          self.port=port          self.user=user          self.passwd=passwd          self.db=db          self.charset=charset      #創建一個鏈接      def connection(self):          #1. 創建連接          self.conn = pymysql.connect(host=self.host, port=self.port, user=self.user, passwd=self.passwd, db=self.db,charset=self.charset)          #2. 創建游標          self.cur = self.conn.cursor()      #關閉鏈接      def closeconnection(self):          self.cur.close()          self.conn.close()      #查詢一條數據      def getonedata(self,sql):          try:              self.connection()              self.cur.execute(sql)              result=self.cur.fetchone()              self.closeconnection()          except Exception:              print(Exception)          return result      #查詢多條數據      def getalldata(self,sql):          try:              self.connection()              self.cur.execute(sql)              result=self.cur.fetchall()              self.closeconnection()          except Exception:              print(Exception)          return result      #添加/修改/刪除      def executedata(self,sql):          try:              self.connection()              self.cur.execute(sql)              self.conn.commit()              self.closeconnection()          except Exception:              print(Exception)       

封裝好了以後,後續用到mysql的操作的地方都可以直接使用,栗子如下:

from mysqlhelper import *    db=dbhelper(host='127.0.0.1', port=3306, user='root', passwd='123456', db='school',charset="utf8")  result=db.getalldata("select * from class")  print(result)