用pd.DataFrame.to_sql方法插入万行数据耗时21秒

to_sql是Pandas中用于将DataFrame数据写入数据库的方法,可以将DataFrame转换为SQL语句,方便我们将数据存入数据库中,以便进行后续的操作。

to_sql方法中包含多个参数,比较常用的参数有name(表名)、con(数据库连接对象)、if_exists(若表已经存在,进行何种操作)、index(将DataFrame的index列写入数据库中)等。

pandas.read_sql(sql, con, index_col=None, coerce_float=True, params=None, parse_dates=None, columns=None, chunksize=None, dtype_backend=_NoDefault.no_default, dtype=None)
Read SQL query or database table into a DataFrame.

pandas.read_sql — pandas 2.1.2 documentation

def to_sql(frame,name: str,con,schema: str | None = None,if_exists: Literal["fail", "replace", "append"] = "fail",index: bool = True,index_label: IndexLabel | None = None,chunksize: int | None = None,dtype: DtypeArg | None = None,method: Literal["multi"] | Callable | None = None,engine: str = "auto",**engine_kwargs,
) -> int | None:"""Write records stored in a DataFrame to a SQL database.Parameters----------frame : DataFrame, Seriesname : strName of SQL table.con : SQLAlchemy connectable(engine/connection) or database string URIor sqlite3 DBAPI2 connectionUsing SQLAlchemy makes it possible to use any DB supported by thatlibrary.If a DBAPI2 object, only sqlite3 is supported.schema : str, optionalName of SQL schema in database to write to (if database flavorsupports this). If None, use default schema (default).if_exists : {'fail', 'replace', 'append'}, default 'fail'- fail: If table exists, do nothing.- replace: If table exists, drop it, recreate it, and insert data.- append: If table exists, insert data. Create if does not exist.index : bool, default TrueWrite DataFrame index as a column.index_label : str or sequence, optionalColumn label for index column(s). If None is given (default) and`index` is True, then the index names are used.A sequence should be given if the DataFrame uses MultiIndex.chunksize : int, optionalSpecify the number of rows in each batch to be written at a time.By default, all rows will be written at once.dtype : dict or scalar, optionalSpecifying the datatype for columns. If a dictionary is used, thekeys should be the column names and the values should be theSQLAlchemy types or strings for the sqlite3 fallback mode. If ascalar is provided, it will be applied to all columns.method : {None, 'multi', callable}, optionalControls the SQL insertion clause used:- None : Uses standard SQL ``INSERT`` clause (one per row).- ``'multi'``: Pass multiple values in a single ``INSERT`` clause.- callable with signature ``(pd_table, conn, keys, data_iter) -> int | None``.Details and a sample callable implementation can be found in thesection :ref:`insert method <io.sql.method>`.engine : {'auto', 'sqlalchemy'}, default 'auto'SQL engine library to use. If 'auto', then the option``io.sql.engine`` is used. The default ``io.sql.engine``behavior is 'sqlalchemy'.. versionadded:: 1.3.0**engine_kwargsAny additional kwargs are passed to the engine.Returns-------None or intNumber of rows affected by to_sql. None is returned if the callablepassed into ``method`` does not return an integer number of rows... versionadded:: 1.4.0Notes-----The returned rows affected is the sum of the ``rowcount`` attribute of ``sqlite3.Cursor``or SQLAlchemy connectable. The returned value may not reflect the exact number of writtenrows as stipulated in the`sqlite3 <https://docs.python.org/3/library/sqlite3.html#sqlite3.Cursor.rowcount>`__ or`SQLAlchemy <https://docs.sqlalchemy.org/en/14/core/connections.html#sqlalchemy.engine.BaseCursorResult.rowcount>`__"""  # noqa: E501if if_exists not in ("fail", "replace", "append"):raise ValueError(f"'{if_exists}' is not valid for if_exists")if isinstance(frame, Series):frame = frame.to_frame()elif not isinstance(frame, DataFrame):raise NotImplementedError("'frame' argument should be either a Series or a DataFrame")
  • 读取表格,插入测试: 

import pandas as pd
import pyodbc
import openpyxl
from sqlalchemy import create_engine# Connection parameters
server = 'localhost'
database = 'tsl'
username = 'sa'
password = 'lqxxx'# Create a SQLAlchemy engine
engine = create_engine(f"mssql+pyodbc://{username}:{password}@{server}/{database}?driver=ODBC Driver 17 for SQL Server")#设置文件目录
filePath = r"C:\\Users\\Administrator\\Documents\\traindata20221231.xlsx"#读取excel文件"明细"页签数据
table = pd.read_excel(filePath,sheet_name="Sheet0")print(table.info())#连接测试,验证能否连通
try:pd.read_sql('Employees', con=engine); print("connect successfully!")
except Exception as error:print("connect fail! because of :", error)# import time
# T1 = time.time()
# #用to_sql()方法插入数据,if_exists参数值:"replace"表示如果表存在, 则删掉重建该表, 重新创建;"append"表示如果表存在, 则会追加数据。
# try:
#     table.to_sql("trading", con=engine, index=False, if_exists="replace");
#     print("insert successfully!")
# except Exception as error: 
#     print("insert fail! because of:", error)
# print("data write complete!")
# T2 = time.time()
# print('程序运行时间:%s毫秒' % ((T2 - T1)*1000))# <class 'pandas.core.frame.DataFrame'>
# RangeIndex: 10233 entries, 0 to 10232
# Data columns (total 11 columns):
#  #   Column          Non-Null Count  Dtype  
# ---  ------          --------------  -----  
#  0   tradingHours    10233 non-null  object 
#  1   tradingChannel  10233 non-null  object 
#  2   currencyType    10233 non-null  object 
#  3   changeInto      10233 non-null  float64
#  4   changeOut       10233 non-null  float64
#  5   balance         10233 non-null  float64
#  6   tradingName     10141 non-null  object 
#  7   tradingAccount  10153 non-null  object 
#  8   paymentMethod   10233 non-null  object 
#  9   postscript      8099 non-null   object 
#  10  summary         916 non-null    object 
# dtypes: float64(3), object(8)
# memory usage: 879.5+ KB
# None
# connect successfully!
# insert successfully!
# data write complete!
# 程序运行时间:20926.252126693726毫秒
# [Finished in 39.9s]

若数据库表已存在,且没有指定if_exists参数,则to_sql方法默认行为为追加数据,即写入新数据时不会覆盖原有数据。此时需要注意数据重复问题。
to_sql方法写入大量数据时,可能会导致内存不足,需要使用chunksize参数进行分批写入。
to_sql方法写入数据时,默认使用pandas.DataFrame.to_sql(),可能存在性能问题

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/127127.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【算法挑战】用栈实现队列(含解析、源码)

232.用栈实现队列 https://leetcode-cn.com/problems/implement-queue-using-stacks/ 232.用栈实现队列 题目描述方法 1 思路复杂度代码 方法 2 思路复杂度代码(JavaScript/C) 题目描述 使用栈实现队列的下列操作&#xff1a;push(x) -- 将一个元素放入队列的尾部。 pop(…

系统架构设计师-第15章-面向服务架构设计理论与实践-软考学习笔记

面向服务的体系结构&#xff08;Service-Oriented Architecture, SOA) 面向服务的体系结构&#xff08;Service-Oriented Architecture, SOA&#xff09;是一种软件架构模式&#xff0c;它将应用程序的不同功能组织为一组可重用的、松耦合的、自治的服务&#xff0c;这些服务通…

在前端实现小铃铛上展示消息

点击铃铛显示如下消息框&#xff1a; 如果点击消息&#xff0c;可以实现消息从列表中移除,并从铃铛总数上进行扣减对应的已读消息数。 关于以上功能的实现方式&#xff1a; <!-- 铃铛位置 --><i class"el-icon-bell" click"showPopover true"&…

ubuntu启动报错error: proc_thermal_add, will cont

如题&#xff0c;ubuntu启动报错error: proc_thermal_add, will cont 截图如下&#xff1a; 困扰了我很久&#xff0c;差点就打算重装系统&#xff0c;准备放弃了&#xff0c;但是感谢国外的老哥&#xff0c;写了一篇非常详细的解决方案&#xff0c;我搬过来。 解决方案&#…

03-对象

对象 对象1.对象的创建字面量模式构造函数模式 2.对象的访问3.新增删除对象中的属性4.Object显示类型转换(强制类型转换)ECMAScript中可用的3种强制类型转换如下&#xff1a;Boolean(value)String(value)Number(value)Object类型到Boolean类型Object类型转String类型转换规则&a…

Redis通过复制rdb文件方式同步线上数据到本地以及提示:Can‘t handle RDB format version 9解决

场景 Redis的持久化机制-RDB方式和AOF方式&#xff1a; Redis的持久化机制-RDB方式和AOF方式_rdb 和ao-CSDN博客 Redis持久化机制导致服务自启动后恢复数据过长无法使用以及如何关闭&#xff1a; Redis持久化机制导致服务自启动后恢复数据过长无法使用以及如何关闭_霸道流氓…

mysql数据表设计

命名 mysql表名的命名规范为表名可以用 t_ 、tb_的前缀&#xff0c;或者是业务模块前缀。比如t_order。 有些项目也会使用 tt_、tm_、 ts_ 等前缀&#xff0c;根据项目的习惯命名就好了。 主键&#xff1a; AUTO_INCREMENT 表示自增&#xff0c;UNSIGNED 表示无符号&#xf…

【算法专题】双指针—盛最多水的容器

一、题目解析 分析这个题目不难得出一个容积公式 二、算法原理 解法一&#xff1a;暴力枚举&#xff08;超时&#xff09; 套用上述的容积公式&#xff0c;使用两个for循环来枚举出所有可能的情况&#xff0c;再挑出最大值即可&#xff0c;但是这种写法会超时&#xff0c;导致…

数据结构-初识泛型

写在前&#xff1a; 这一篇博客主要来初步的记录以下泛型的相关内容&#xff0c;内容比较琐碎&#xff0c;就不进行目录的整合&#xff0c;后续可能会对泛型这里进行系统性的梳理&#xff0c;此篇博客主要是对泛型有一个简单的认识与理解&#xff0c;需要知晓的内容。 当我调用…

2. 网络之网络编程

网络编程 文章目录 网络编程1. UDP1.1 DatagramSocket1.1.1 DatagramSocket 构造方法1.1.2 DatagramSocket 方法&#xff1a; 1.2 DatagramPacket1.2.1 DatagramPacket构造方法1.2.2 DaragramPacket方法1.2.3InetSocketAddress API 1.3 UDP回显服务器1.3.1 框架结构1.3.2 读取请…

将图像的锯齿状边缘变得平滑的方法

项目背景 使用PaddleSeg 192x192 模型分割出来的目标有锯齿状边缘&#xff0c;想通过传统算法将这种锯齿状边缘的变得平滑&#xff0c;虽然试了很过方法&#xff0c;但是效果还是不太理想 常用的集中方法 当使用分割算法&#xff08;如分水岭分割、阈值分割等&#xff09;分…

Docker:命令

Docker&#xff1a;命令 1. 创建MySQL的命令解读2. 基础命令3. 案例 查看DockerHub&#xff0c;拉取Nginx镜像&#xff0c;创建并运行Nginx容器4. 命令别名附录 1. 创建MySQL的命令解读 docker run :创建并运行一个容器&#xff0c;-d 是让容器在后台运行--name:给容器起一个名…

使用脚本整合指定文件/文件夹,执行定制化 ESLint 命令

背景 最近面对一个庞大的项目&#xff0c;但是只需要修改某个模块&#xff0c;每次都手搓命令太麻烦了&#xff0c;于是就想着能不能写个脚本来辅助处理这些事情。 解决方案 定制化一键 ESLint&#xff0c;执行文件下载地址&#xff1a; https://github.com/mazeyqian/go-g…

Python 自动化(十六)静态文件处理

准备工作 将不同day下的代码分目录管理&#xff0c;方便后续复习查阅 (testenv) [rootlocalhost projects]# ls day01 day02 (testenv) [rootlocalhost projects]# mkdir day03 (testenv) [rootlocalhost projects]# cd day03 (testenv) [rootlocalhost day03]# django-admi…

基于nodejs+vue啄木鸟便民维修网站设计与实现

目 录 摘 要 I ABSTRACT II 目 录 II 第1章 绪论 1 1.1背景及意义 1 1.2 国内外研究概况 1 1.3 研究的内容 1 第2章 相关技术 3 2.1 nodejs简介 4 2.2 express框架介绍 6 2.4 MySQL数据库 4 第3章 系统分析 5 3.1 需求分析 5 3.2 系统可行性分析 5 3.2.1技术可行性&#xff1a;…

element-plus走马灯不显示

问题描述 依赖正确&#xff0c;代码用法正确&#xff0c;但是element-plu走马灯就是不显示&#xff01;&#xff01; <div class"content"><el-carousel height"150px" width"200px"><el-carousel-item v-for"item in 4&qu…

Android 默认关闭自动旋转屏幕功能

Android 默认关闭自动旋转屏幕功能 接到客户邮件想要默认关闭设备的自动旋转屏幕功能&#xff0c;具体修改参照如下&#xff1a; /vendor/mediatek/proprietary/packages/apps/SettingsProvider/res/values/defaults.xml - <bool name"def_accelerometer_rotati…

代码随想录图论并查集 | 第六天 1971. 寻找图中是否存在路径 684.冗余连接

代码随想录图论并查集 | 第六天 1971. 寻找图中是否存在路径 684.冗余连接 一、1971. 寻找图中是否存在路径 题目链接&#xff1a;https://leetcode.cn/problems/find-if-path-exists-in-graph/ 思路&#xff1a;典型并查集模板题。 class Solution {int[] father null;pub…

1、Flink基础概念

1、基础知识 &#xff08;1&#xff09;、数据流上的有状态计算 &#xff08;2&#xff09;、框架和分布式处理引擎&#xff0c;用于对无界和有界数据流进行有状态计算。 &#xff08;3&#xff09;、事件驱动型应用&#xff0c;有数据流就进行处理&#xff0c;无数据流就不…

【LeetCode热题100】两数之和 C++

给定一个整数数组 nums 和一个整数目标值 target&#xff0c;请你在该数组中找出 和为目标值 target 的那 两个 整数&#xff0c;并返回它们的数组下标。 你可以假设每种输入只会对应一个答案。但是&#xff0c;数组中同一个元素在答案里不能重复出现。 你可以按任意顺序返回…