Python读写Mysql数据库

叶景龙
2023-12-01

一、简介

这是一个可以直接使用的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),))

 类似资料: