【Python】pymysql操作数据库-插入数据

本文介绍如何使用Python及pandas库从CSV文件中读取数据并导入到MySQL数据库的过程。具体步骤包括:创建数据库表、连接MySQL、读取CSV文件、处理数据并执行SQL插入操作。
摘要由CSDN通过智能技术生成

一、创建有如下数据库

1.1创建数据库user5

mysql> use mytest;
Database changed
mysql> create table if not exists user5(
    -> id int not null key auto_increment,
    -> symbol char(10) not null default '',
    -> name varchar(30) not null default '',
    -> type tinyint(3) not null default 0,
    -> buy_date date ,
    -> sell_date date ,
    -> strategy int(10) not null default 0,
    -> hot varchar(100) not null default '',
    -> hot_rel double not null default 0,
    -> result tinyint(3) not null default 0,
    -> return_rate decimal(10) default 0,
    -> max_return_rate decimal(10) default 0,
    -> status tinyint(3) not null default 0)engine=innodb charset=utf8;
Query OK, 0 rows affected (0.02 sec)

这里写图片描述

1.2待导入的数据
这里写图片描述

二、Python脚本运行导入数据

# -*- coding: utf-8 -*-
import pymysql
import pymysql.cursors
import pandas as pd


# 连接MySQL数据库
connection = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='123456', db='mytest', 
                             charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)

# 通过cursor创建游标
cursor = connection.cursor()

#导入数据集
datas = pd.read_csv('stock_data.csv',encoding = 'gb2312',index_col = 0)

symbols = datas['symbol'].values[-1]
#对symbols处理,读取的股票代码如果开头有0时会被略掉
if len(str(symbols))!=6:
    N = 6-len(str(symbols))
    for i in range(N):
        symbols = (str(0)+str(symbols))
#print(symbols)
names = datas['name'].values[-1]
typess = datas['types'].values[-1]
buy_dates = datas['buy_date'].values[-1]
sell_dates = datas['sell_date'].values[-1]
strategys = datas['strategy'].values[-1]
hots = datas['hot'].values[-1]
hot_rels = datas['hot_rel'].values[-1]
results = datas['result'].values[-1]

sql = "INSERT INTO user5(symbol,name,types,buy_date,sell_date,strategy,hot,hot_rel,result) VALUES('%s','%s','%s','%s','%s','%s','%s','%s','%s')"
#sql = "INSERT INTO user5( name,types,buy_date,sell_date,strategy,hot,hot_rel,result) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s)"
# 创建sql语句,并执行
#sql = "INSERT INTO user2(love, name) VALUES('yes', 'brucce')"
cursor.execute(sql%(str(symbols),str(names),str(typess),str(buy_dates),str(sell_dates),str(strategys),str(hots),str(hot_rels),str(results)))
#cursor.execute(sql,(str(names),str(typess),str(buy_dates),str(sell_dates),str(strategys),str(hots),str(hot_rels),str(results)))
# 提交SQL
connection.commit()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值