python连接Navicat线上数据库并将excel表格中的内容导入进去

python连接Navicat线上数据库并将excel表格中的内容导入进去

import time
import pymysql
import xlrd

# 连接数据库
try:
	#financial为数据库名
    db = pymysql.connect(host='xxx', port=3306, user='xxx', password='xxx', db='financial')
except:
    print("could not connect to mysql server")

# 打开excel表格
def open_excel():
    try:
        # file_path为路径
        current_time = time.strftime('%Y-%m-%d', time.localtime())
        file_name = current_time + ".xlsx"
        file_path = "D:\python代码\eastmoneytry\eco_dashangsuo" + "\\" + file_name
        book = xlrd.open_workbook(file_path)
    except:
        print("open excel file failed!")
    try:
        # execl里面的sheet1名字
        sheet = book.sheet_by_name("期货市场大商所")
        return sheet
    except:
        print("locate worksheet in excel failed!")

# 往数据库里插入表格数据
def insert_deta():
    sheet = open_excel()
    cursor = db.cursor()
    # 获取excel表格的竖行
    row_num = sheet.nrows
    # 第一行是标题名,对应表中的字段名所以应该从第二行开始,计算机以0开始计数,所以值是1
    for i in range(0, row_num):  
        # row_data是表格的竖行,有多少竖行要导入就要有多少row_data[]
        row_data = sheet.row_values(i)
        value = (row_data[0], row_data[1], row_data[2], row_data[3],row_data[4], row_data[5], row_data[6], row_data[7],row_data[8], row_data[9], row_data[10], row_data[11],row_data[12], row_data[13], row_data[14])
        # print(i)
        sql = "INSERT INTO aaa(id,e_name,name,last_price,ud_price,u,begin,high,low,y_finish,cjl,money,buy,hava,cell)VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s )"
        # 执行sql语句
        cursor.execute(sql, value)
        db.commit()
    # 关闭连接
    cursor.close()

def update():
    cursor = db.cursor()
    # 往数据库中的date插入数据,内容为当天的时间
    update="update aaa set date=CURDATE() where date is null"
    cursor.execute(update)
    db.commit()
    cursor.close()

def remove():
    cursor = db.cursor()
    # 删除数据库中id为0的数据
    remove = "DELETE  from aaa WHERE id='0'"
    cursor.execute(remove)
    db.commit()
    cursor.close()

open_excel()
insert_deta()
update()
remove()

用这段代码前可以先把期货市场大商所的数据爬取下来
爬取代码见另一篇https://blog.csdn.net/m0_50481455/article/details/108724684

本文依照此链接进行了修改
参考链接https://www.cnblogs.com/longbigbeard/p/9309180.html

猜你喜欢

转载自blog.csdn.net/m0_50481455/article/details/108664599
今日推荐