Python读写Mysql数据库

一、简介

这是一个可以直接使用的python数据库demo。

  1. queryAll方法:查询表数据
  2. outfile方法:导出数据为Excel
  3. infile方法:使用Excel导入数据库
  4. inserts方法:批量插入数据库
  5. executes方法:执行sql语句

二、使用方法

修改if __name__ == "__main__"下的代码即可。

# -*- coding:utf-8 -*-
import pymysql
from openpyxl import Workbook


class Database:
    def __init__(self, connection):
        cursor = connection.cursor()
        self.cursor = cursor
        self.connection = connection

    def queryAll(self, table):
        sql = 'select * from {};'.format(table)
        self.cursor.execute(sql)
        result = self.cursor.fetchall()
        fields = [i[0] for i in self.cursor.description]

        print(fields)
        for i in result:
            print(i)

    def close(f):
        def test(self, *args, **kwargs):
            f(self, *args, **kwargs)
            # 关闭连接
            self.connection.close()
            # 关闭游标
            self.cursor.close()
            print("成功关闭连接和游标.")

        return test

    @close
    def outfile(self, table):
        sql = 'select * from {};'.format(table)
        self.cursor.execute(sql)
        result = self.cursor.fetchall()
        headers = [i[0] for i in self.cursor.description]

        wb = Workbook()
        sheet = wb.active
        # 写入表头
        sheet.append(headers)
        # 获取并写入数据段信息
        for index, i in enumerate(result):
            sheet.append(list(i))
            print('正在保存第' + str(index) + '列信息')
        wb.save(f"{table}.xlsx")

    @close
    def infile(self, path, table):

        """
        加载文件,
        替换到xx表格,
        编码设置utf-8,
        字段以逗号结尾,
        换行符以\r\n结尾,
        忽略第一行;
        """

        data_sql = "LOAD DATA LOCAL INFILE '%s' REPLACE INTO TABLE %s CHARACTER SET UTF8 FIELDS TERMINATED BY '," \
                   "' LINES TERMINATED BY '\\r\\n' IGNORE 1 LINES" % (
                       path, table)

        self.cursor.execute(data_sql)
        self.connection.commit()
        print("数据提交成功!")

    @close
    def inserts(self, sql, *val):
        """
        多条数据插入
        "insert into words (id,field1,field2) value (%s,%s,%s)"
        """

        self.cursor.executemany(sql, *val)
        self.connection.commit()
        print("成功插入数据")
        print(self.cursor.rowcount)

    @close
    def executes(self, sql, val):
        self.cursor.executemany(sql, val)


if __name__ == "__main__":
    db = pymysql.connect(host='localhost',
                         user='root',
                         password='1234',
                         database='how2java',
                         local_infile=True)
    db = Database(db)
    db.inserts("insert into hero (name,hp,damage) value (%s,%s,%s)", (("阿狸", 1000, 50),))

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

弄堂汪

看了觉得好,就请我喝瓶水吧!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值