python快速写入sql

CREATE TABLE `ele` (
`price` int(11) DEFAULT NULL COMMENT '价格',
`qiyou` VARCHAR(100) DEFAULT NULL COMMENT '汽油', 
`caiyou` VARCHAR(100) DEFAULT NULL COMMENT '柴油', 
`pele` VARCHAR(100) DEFAULT NULL COMMENT '全国发电量', 
`uele` VARCHAR(100) DEFAULT NULL COMMENT '全国全社会用电量', 
`phot` VARCHAR(100) DEFAULT NULL COMMENT '全国供热量', 
`ucoal` VARCHAR(100) DEFAULT NULL COMMENT '全国供热耗用原煤', 
`ppele` VARCHAR(100) DEFAULT NULL COMMENT '全国供电量',
`ds` datetime NOT NULL COMMENT '日期', 
PRIMARY KEY (`ds`) USING BTREE ) 
ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

da是dataframe

import requests
import pymysql
import sys
import json
from lxml import etree
from fake_useragent import UserAgent
from pyquery import PyQuery as pq

import time
import requests
import csv
import random

#连接数据库
def get_conn(database="coal"):
    conn=pymysql.connect(
    host="localhost",port=3306,
    user="root",password="123456",
    database=database,charset="utf8"
    )
    cursor=conn.cursor()
    return conn,cursor
#释放资源
def close(conn,cursor):
    cursor.close()
    conn.close()

    
conn,sursor=get_conn()
sql="insert into ele values(%s,%s,%s,%s,%s,%s,%s,%s,%s)"
for i in range(0,da.index.stop):
    d=list(da.loc[i])
    sursor.execute(sql,d)
    #提交事务
    conn.commit()
print("数据更新完毕!!!")
close(conn,sursor)

before={}

for l in range(0,coalbefore.index.stop):
    li=list(coalbefore.loc[l])
    
    before[li[-1]]={'ds':li[-2],
                  'kindprice':li[-3],
                  'weekradio':li[-4],
                  'price':li[2],
                  'place':li[0],
                  'kind':li[1]
                  }
    
#连接
conn,sursor=get_conn()

sql="insert into coalbefore values(%s,%s,%s,%s,%s,%s,%s)"
#写入数据库
for k,v in before.items():
    sursor.execute(sql,[v.get('ds'),
                        v.get('place'),
                        v.get('kind'),
                        k,
                        v.get('price'),
                        v.get('kindprice'),
                        v.get('weekradio')
                        ])
    #提交事务
    conn.commit()
print("数据更新完毕!!!")
close(conn,sursor)

你可能感兴趣的:(开发,sql,python,数据库)