我认为最快的方法是在数据库本身中执行所有插入/更新,而不是连接到它并使用大量语句。
请注意,这是特定于 Oracle 的,但其他数据库可能有类似的概念。
我将使用以下方法:首先将 Excel 数据保存为数据库服务器 ( /mydatadir/mydata.csv
) 上的 CSV 文件,然后在 Oracle 中我将使用外部表:
create or replace directory data_dir as '/mydatadir/';
create table external_table (
id number(18),
name varchar2(30),
otherfield1 varchar2(40),
otherfield2 varchar2(40))
organization external (
type oracle_loader
default directory data_dir
access parameters
( fields terminated by ',' )
location ('mydata.csv')
)
(注意,不必每次都设置外部表)
然后您可以使用以下命令将数据合并到您的表中:
merge into yourtable t
using external_table e
on t.name = e.name
when matched then
update set t.id = e.id,
t.otherfield1 = e.otherfield1,
t.otherfield2 = t.otherfield2
when not matched then
insert (t.id, t.name, t.otherfield1, t.otherfield2)
values (e.id, e.name, e.otherfield1, e.otherfield2)
这将在一个 Oracle 命令中更新行yourtable
,因此所有工作都将由数据库执行。
编辑:
此merge
命令可以通过普通 JDBC 发出(尽管我更喜欢使用 Spring 的SimpleJdbcTemplate)
编辑2:
在 MySQL 中,您可以使用以下构造来执行合并:
insert into yourtable (id, name, otherfield1, otherfield2)
values (?, ?, ?, ?),
(?, ?, ?, ?),
(?, ?, ?, ?) --repeat for each row in the Excel sheet...
on duplicate Key update
set otherfield1 = values(otherfield1),
otherfield2 = values(otherfield2)
这可以作为一个普通的 JDBC 语句发出,并且比单独的更新和插入要好,您可以从电子表格中分批(比如说)一百行调用这些语句。这意味着您的 Excel 工作表中每 100 行有 1 次 JDBC 调用,并且应该表现良好。这将允许您在没有外部表的情况下执行此操作(您需要 name 列上的唯一索引才能工作,我不会更改主键,因为如果您需要更改,这可能会导致外键出现问题某人的名字)。
MySQL 也有external tables的概念,我认为这比按照上面的批量插入数据要快。只要将 csv 文件上传到正确的位置,导入应该会很快进行。