pymysql-增删改查

一、实例

import os
import sys
import pymysql

'''
该类主要功能是链接数据库然后执行查询,反馈想要的结果
'''

curPath = os.path.abspath(os.path.dirname(__file__))
rootPath = os.path.split(curPath)[0]
sys.path.append(rootPath)

class Mysql():

    # 初始化数据库
    def __init__(self, host, port, db, user, password, charset='utf8'):
        self.db = pymysql.connect(host=host, port=port, db=db, user=user, password=password,)  #打开数据库连接
        self.cursor = self.db.cursor()          # 使用cursor()方法创建一个游标对象cursor

    # 执行查询
    def sql_result(self, sql):
        try:
            self.cursor.execute(sql)    #使用execute()方法执行SQL查询
            data = self.cursor.fetchall()    #使用fetchall()方法获取所有数据
            return list(data)
        except:
            raise ValueError('查询出错')
        finally:
            self.cursor.close()  # 关闭游标
            self.db.close()     # 关闭数据库

    # 更新语句
    def update(self, sql):
        try:
            self.cursor.execute(sql)  # 使用execute()方法执行SQL查询
            self.db.commit()   #提交到数据库执行
        except:
            self.db.rollback()          #发生错误时回滚
        finally:
            self.cursor.close()         #关闭游标
            self.db.close()             # 关闭数据库

    # 删除语句
    def delete(self, sql):
        try:
            self.cursor.execute(sql)  # 使用execute()方法执行SQL查询
            self.db.commit()  # 提交到数据库执行
        except:
            self.db.rollback()              # 发生错误时回滚
        finally:
            self.cursor.close()             # 关闭游标
            self.db.close()                 #关闭数据库

    # 查询结果转换
    def reslut_replace(self, sql):
        result = self.sql_result(sql)
        if result == []:
            result = ''
        else:
            result = result[0][0]
        return str(result)

    # 执行其他操作
    def user_database(self, sql):
        self.cursor.execute(sql)

if __name__ == "__main__":
    db = Mysql(user='mysql', db='testdevplatform', password='哈哈哈哈哈哈', host='localhost', port=3306, charset='utf8')
    sql = "select * from world.city "
    data = db.sql_result(sql)
    print(data)

1、data = cursor.fetchone() #使用fetchane()方法获取单条数据
data = self.cursor.fetchall() #使用fetchall()方法获取所有数据
2、== cursor.execute(sql) # 执行sql语句==
== db.commit() #提交到数据库执行==
db.rollback() #如果发生错误则回滚
3、commit()方法游标的所有更新操作,rollback()方法回滚当前游标的所有操作。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值