excel文件數據導入到數據庫中

import xlrd
import pymysql
import datetimemysql

def open_excel():
    book = xlrd.open_workbook("D:\Documents\Downloads\XX.xls")  # 文件名,把文件與py文件放在同一目錄下
    sheet = book.sheet_by_index(0)
    return sheetsql


# 鏈接數據庫數據庫

db = pymysql.connect(
                         host="XX",
                         user="dc",
                         passwd="Password@dc",
                         db="ods",
                         charset='utf8'
)fetch


def search_count():
    cursor = db.cursor()
    select1 = "truncate table ori_zm_case_pro_main_temp"  # 獲取表中ori_zm_case_pro_main_temp記錄數
    cursor.execute(select1)  # 執行sql語句
    # select2 = "select count(case_id) from ori_zm_case_pro_main_temp"  # 獲取表中ori_zm_case_pro_main_temp記錄數
    # cursor.execute(select2)  # 執行sql語句
    # line_count = cursor.fetchone()
    # print(line_count[0])excel


def insert_deta():
    sheet = open_excel()
    cursor = db.cursor()
    now_date = datetime.datetime.now().strftime('%Y-%m-%d')
    now_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    for i in range(1, sheet.nrows):  # 第一行是標題名,對應表中的字段名因此應該從第二行開始,計算機以0開始計數,因此值是1
        case_input_code = sheet.cell(i, 0).value  # 取第i行第0列
        discover_type = sheet.cell(i, 1).value
        case_hap_date = sheet.cell(i, 2).value
        item_name = sheet.cell(i, 3).value
        from_pro = sheet.cell(i, 4).value
        from_city = sheet.cell(i, 5).value
        cust_counts = sheet.cell(i, 6).value
        item_counts = sheet.cell(i, 7).value
        op_date = now_date
        op_time = now_time
        value = (case_input_code, discover_type,case_hap_date,item_name,from_pro,from_city,cust_counts,item_counts,op_date,op_time)
        # print(value)
        sql = "INSERT INTO ori_zm_case_pro_main_temp(case_input_code, discover_type,case_hap_date,item_name,from_pro,from_city,cust_counts,item_counts,op_date,op_time)VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
        cursor.execute(sql, value)  # 執行sql語句
        db.commit()
    cursor.close()  # 關閉鏈接code

search_count()
insert_deta()ci

db.close()  # 關閉數據
print("ok ")input

相關文章
相關標籤/搜索