2 个简单的 python 脚本,连接 MySQL 和读取 Excel

python脚本

第一次写博客,已经工作一年半了,从事PHP后端,最近尝试新语言,换换胃口,看了看go和python,最后选择了python。刚好上周遇到读取excel,编写sql导入数据库的工作,尝试写个脚本。下次就不用重复写了。

运行环境:

  • python 3.8.1
  • windows 7

一。连接mysql

连接mysql有很多种方式:pymysql mysql-connector mysqldb。之前看到的一篇性能分析上,非ORM操作mysqldb性能最佳,ORM操作mysql-connector性能最佳。脚本暂时不涉及性能方面的问题,就选择了pymysql。

安装依赖库

pip3 install PyMySQL

脚本

import pymysql

def runSql(sql):

    db = pymysql.connect(host="127.0.0.1",
                         port=3306,
                         user="test",
                         password="test",
                         db="test",
                         charset="utf8")

    #这个是控制返回的数据结构为字典的,即把数据表里的字段名作为key返回
    # cursor = db.cursor(cursor=pymysql.cursors.DictCursor)
    cursor = db.cursor()
    try:
        cursor.execute(sql)

        results = cursor.fetchall()

    except:
        print("error")

    db.close()
    return results
#pip3 install PyMySQL

二. 读取excel

python 对excel的处理有xlrd/xlwt与openpyxl ,查阅的性能分析结果是,对大文件的处理xlrd/xlwt性能更高,暂时对性能分析没有深入接触,没有遇到性能瓶颈,脚本暂时不考虑这些,这里使用xlrd/xlwt。

安装依赖库

pip3 install xlrd

脚本

import xlrd

table = xlrd.open_workbook(r'C:.sers.dministrator.esktop.ead.xlsx')

sheet = table.sheet_by_name('Sheet1')  # 根据名字取表单

nrows = sheet.nrows  # 获取行数

line = 1
while line < nrows:
    a = sheet.cell(line, 1).value
    b = sheet.cell(line, 2).value
    line += 1

其他相关方法

name = table.sheet_names()  # 获得所有表单的名字
ncols = sheet.ncols   # 获取列数

结语

上面的2个依赖库里还有很多的方法,这里暂时没有用到,下次用到再补充。

本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 2
import pymysql

class op_mysql():
    def __init__(self,
    host="127.0.0.1",
    port=3306,
    user="test",
    password="test",
    db="test",
    charset="utf8"):
        self.conn= pymysql.connect(host="127.0.0.1",
                         port=3306,
                         user="test",
                         password="test",
                         db="test",
                         charset="utf8")
        self.cursor = db.cursor()

    def op_sql(self,xx,x):
        pass

    def __del__(self):
        self.cursor.close()
        self.conn.close()

面向对象写法🙃,可能方便些哦~

4年前 评论

@Stray_camel 写php脚本习惯了,只顾着自己当时单个执行的时候方便,确实应该向那个方向规范下 :grimacing:

4年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!