Python如何操做MySQL

安装Mysql和Navicat for MySQL

mysql的安装图解https://jingyan.baidu.com/art...
navicat for mysql破解能够看下这个文章https://www.cnblogs.com/da199...html

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的操做的地方均可以直接使用,栗子以下:python

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)
相关文章
相关标签/搜索