zoukankan      html  css  js  c++  java
  • 从Excel中读取数据并批量写入MySQL数据库(基于pymysql)

    一、Excel内容时这样的:

    二、最初的代码是这样的:

    # -*- coding:utf-8 -*-
    import pymysql
    from xlrd import open_workbook

    class DB:
    global host,username,password,port,database,config
    host = "xx.xx.xx.xxx"
    username = "root"
    password = "xxxx"
    port = 3306
    database = "pythondb"
    config = {
    'host': str(host),
    'user': username,
    'passwd': password,
    'port': int(port),
    'db': database
    }
    def __init__(self):
    self.db = None
    self.cursor = None

    def connectDB(self):
    try:
    self.db = pymysql.connect(**config)
    self.cursor = self.db.cursor()
    print "Connect DB successfully!"
    except:
    print "Connect DB failed!"

    def executeSQL(self,sql):
    self.connectDB()
    self.cursor.execute(sql)
    self.db.commit()
    return self.cursor

    def getAll(self,cursor):
    value = cursor.fetchall()
    return value

    def getOne(self,cursor):
    value = cursor.fetchone()
    return value

    def closeDB(self):
    self.db.close()
    print "Database closed!"

    def get_xls(self,xls_name, sheet_name):
    """
    get interface data from xls file
    :return:
    """
    cls = []
    # open xls file
    file = open_workbook(xls_name)
    # get sheet by name
    sheet = file.sheet_by_name(sheet_name)
    # get one sheet's rows
    nrows = sheet.nrows
    for i in range(1,nrows):
    cls.append(sheet.row_values(i))
    return tuple(cls)

    if __name__ == "__main__":
    mysqlInfo = DB()
    content = mysqlInfo.get_xls("DataSource.xls","Sheet1")
    for i in range(0,len(content)):
    id = content[i][0]
    begin_date = str(content[i][1])
    end_date = content[i][2]
    in_num = content[i][3]
    out_num = content[i][4]
    all_num = content[i][5]
    create_time = content[i][6]
    use_time = content[i][7]
    scope_date = content[i][8]
    sql = "INSERT INTO `day`( ID, BEGIN_DATE, END_DATE, IN_NUM, OUT_NUM, ALL_NUM, CREATE_TIME, USE_TIME, SCOPE_DATE ) VALUES(%s,'%s','%s',%s,%s,%s,'%s',%s,%s)" %(id, begin_date, end_date, in_num, out_num, all_num, create_time, use_time, scope_date)
    mysqlInfo.executeSQL(sql)
    mysqlInfo.closeDB()
  • 相关阅读:
    批处理基础知识-IF
    在Windows 10 x64 编译ReactOS-0.4.5源码并在VMare中运行
    复制20天以前指定的文件夹、子文件夹和子文件至指定目录
    bat(批处理)命令(tomcat 7.0.75 startup.bat 命令集)
    mycat
    mysql
    5种网络IO模型
    Linux常用命令
    mybatis多参数传递,延迟加载,缓存,注解开发
    事务,mybatis
  • 原文地址:https://www.cnblogs.com/python-kp/p/11151006.html
Copyright © 2011-2022 走看看