如何将CSV文件数据导入到PostgreSQL表中?

我如何编写一个从CSV文件导入数据并填充表的存储过程?

看看这篇短文 。


解决方案在这里解释:

创建你的表格:

CREATE TABLE zip_codes (ZIP char(5), LATITUDE double precision, LONGITUDE double precision, CITY varchar, STATE char(2), COUNTY varchar, ZIP_CLASS varchar); 

将CSV文件中的数据复制到表格中:

 COPY zip_codes FROM '/path/to/csv/ZIP_CODES.txt' WITH (FORMAT csv); 

如果您没有权限使用COPY (可在数据库服务器上运行),则可以使用\copy (在db客户机中工作)。 使用与Bozhidar Batsov相同的例子:

创建你的表格:

 CREATE TABLE zip_codes (ZIP char(5), LATITUDE double precision, LONGITUDE double precision, CITY varchar, STATE char(2), COUNTY varchar, ZIP_CLASS varchar); 

将CSV文件中的数据复制到表格中:

 \copy zip_codes FROM '/path/to/csv/ZIP_CODES.txt' DELIMITER ',' CSV 

您也可以指定要读取的列:

 \copy zip_codes(ZIP,CITY,STATE) FROM '/path/to/csv/ZIP_CODES.txt' DELIMITER ',' CSV 

一个快速的方法是使用Python熊猫库(版本0.15或更高)。 这将处理为你创建列 – 尽管显然它为数据类型所做的选择可能不是你想要的。 如果它不完全符合你的要求,你总是可以使用生成的“创建表”代码作为模板。

这是一个简单的例子:

 import pandas as pd df = pd.read_csv('mypath.csv') df.columns = [c.lower() for c in df.columns] #postgres doesn't like capitals or spaces from sqlalchemy import create_engine engine = create_engine('postgresql://username:password@localhost:5432/dbname') df.to_sql("my_table_name", engine) 

下面是一些代码,告诉你如何设置各种选项:

 #Set is so the raw sql output is logged import logging logging.basicConfig() logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO) df.to_sql("my_table_name2", engine, if_exists="append", #options are 'fail', 'replace', 'append', default 'fail' index=False, #Do not output the index of the dataframe dtype={'col1': sqlalchemy.types.NUMERIC, 'col2': sqlalchemy.types.String}) #Datatypes should be [sqlalchemy types][1] 

你也可以使用pgAdmin,它提供了一个GUI来进行导入。 这是在这个线程中显示的 。 使用pgAdmin的优点是它也适用于远程数据库。

尽管与之前的解决方案非常相似,但您仍需要在数据库上放置表。 每个人都有他自己的解决方案,但我通常做的是在Excel中打开CSV,复制标题,在不同的工作表上粘贴特殊的换位符,将相应的数据类型放在下一列,然后复制并粘贴到文本编辑器连同适当的SQL表创建查询就像这样:

 CREATE TABLE my_table ( /*paste data from Excel here for example ... */ col_1 bigint, col_2 bigint, /* ... */ col_n bigint ) 

正如保罗所说,导入工作在pgAdmin:

右键单击表格 – >导入

选择本地文件,格式和编码

这里是德国人pgAdmin的GUI屏幕截图:

pgAdmin导入GUI

类似的事情,你可以用DbVisualizer(我有一个许可证,不知道免费版本)

右键单击一个表 – >导入表格数据…

DbVisualizer导入GUI

这里的大多数其他解决方案都要求您提前/手动创建表格。 在某些情况下这可能不实际(例如,如果目标表中有很多列)。 所以,下面的方法可能会得心应手。

提供csv文件的路径和列数,可以使用以下函数将表加载到将被命名为target_table的临时表:

顶行假定有列名称。

 create or replace function data.load_csv_file ( target_table text, csv_path text, col_count integer ) returns void as $$ declare iter integer; -- dummy integer to iterate columns with col text; -- variable to keep the column name at each iteration col_first text; -- first column name, eg, top left corner on a csv file or spreadsheet begin set schema 'your-schema'; create table temp_table (); -- add just enough number of columns for iter in 1..col_count loop execute format('alter table temp_table add column col_%s text;', iter); end loop; -- copy the data from csv file execute format('copy temp_table from %L with delimiter '','' quote ''"'' csv ', csv_path); iter := 1; col_first := (select col_1 from temp_table limit 1); -- update the column names based on the first row which has the column names for col in execute format('select unnest(string_to_array(trim(temp_table::text, ''()''), '','')) from temp_table where col_1 = %L', col_first) loop execute format('alter table temp_table rename column col_%s to %s', iter, col); iter := iter + 1; end loop; -- delete the columns row execute format('delete from temp_table where %s = %L', col_first, col_first); -- change the temp table name to the name given as parameter, if not blank if length(target_table) > 0 then execute format('alter table temp_table rename to %I', target_table); end if; end; $$ language plpgsql; 
 COPY table_name FROM 'path/to/data.csv' DELIMITER ',' CSV HEADER; 

使用这个SQL代码

  copy table_name(atribute1,attribute2,attribute3...) from 'E:\test.csv' delimiter ',' csv header 

header关键字让DBMS知道csv文件有一个带有属性的头文件

欲了解更多信息,请访问http://www.postgresqltutorial.com/import-csv-file-into-posgresql-table/

个人使用PostgreSQL的经验,还在等待更快的方式。

1.如果文件存储在本地,则首先创建表格骨架:

  drop table if exists ur_table; CREATE TABLE ur_table ( id serial NOT NULL, log_id numeric, proc_code numeric, date timestamp, qty int, name varchar, price money ); COPY ur_table(id, log_id, proc_code, date, qty, name, price) FROM '\path\xxx.csv' DELIMITER ',' CSV HEADER; 

2.当\ path \ xxx.csv在服务器上时,postgreSQL没有访问服务器的权限,您将不得不通过pgAdmin内置的功能导入.csv文件。

右键单击表名称选择导入。

在这里输入图像描述

如果还有问题,请参阅本教程。 http://www.postgresqltutorial.com/import-csv-file-into-posgresql-table/

恕我直言,最便捷的方法是遵循“ 导入CSV数据到postgresql,舒适的方式;-) ”,使用csvsql从csvkit ,这是一个Python软件包可安装通过点。

创建表并具有用于在csv文件中创建表所需的列。

  1. 打开postgres并右键点击要载入的目标表并选择导入,然后在文件选项部分更新以下步骤

  2. 现在以文件名浏览你的文件

  3. 以格式选择csv

  4. 编码为ISO_8859_5

现在转到杂项。 选项和检查标题,然后点击导入。