前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python如何操作MySQL

Python如何操作MySQL

作者头像
py3study
发布2020-01-06 18:29:57
5530
发布2020-01-06 18:29:57
举报
文章被收录于专栏:python3

安装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

代码语言:javascript
复制
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类

代码语言:javascript
复制
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的操作的地方都可以直接使用,栗子如下:

代码语言:javascript
复制
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)
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/10/08 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 安装Mysql和Navicat for MySQL
  • Python链接Mysql的增删改查
  • 自己封装helper类
相关产品与服务
云数据库 SQL Server
腾讯云数据库 SQL Server (TencentDB for SQL Server)是业界最常用的商用数据库之一,对基于 Windows 架构的应用程序具有完美的支持。TencentDB for SQL Server 拥有微软正版授权,可持续为用户提供最新的功能,避免未授权使用软件的风险。具有即开即用、稳定可靠、安全运行、弹性扩缩等特点。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档