如何编写从CSV文件导入数据并填充表的存储过程?
当前回答
这是我个人使用PostgreSQL的经验,我还在等待更快的方法。
Create a table skeleton first if the file is stored locally: 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; When the \path\xxx.csv file is on the server, PostgreSQL doesn't have the permission to access the server. You will have to import the .csv file through the pgAdmin built in functionality. Right click the table name and choose import.
如果您仍然有问题,请参考本教程:导入CSV文件到PostgreSQL表
其他回答
我创建了一个小工具,可以超级简单地将csv文件导入PostgreSQL。它只是一个命令,它将创建和填充表,但不幸的是,目前自动创建的所有字段都使用TEXT类型:
csv2pg users.csv -d ";" -H 192.168.99.100 -U postgres -B mydatabase
该工具可以在https://github.com/eduardonunesp/csv2pg上找到
正如Paul提到的,导入在pgAdmin中起作用:
右键单击表→导入
选择一个本地文件,格式和编码。
这是一个德文pgAdmin GUI截图:
使用DbVisualizer也可以做类似的事情(我有许可证,但不确定是否有免费版本)。
右键单击表→导入表数据…
如果你需要一个简单的机制来导入文本/解析多行CSV内容,你可以使用:
CREATE TABLE t -- OR INSERT INTO tab(col_names)
AS
SELECT
t.f[1] AS col1
,t.f[2]::int AS col2
,t.f[3]::date AS col3
,t.f[4] AS col4
FROM (
SELECT regexp_split_to_array(l, ',') AS f
FROM regexp_split_to_table(
$$a,1,2016-01-01,bbb
c,2,2018-01-01,ddd
e,3,2019-01-01,eee$$, '\n') AS l) t;
DBFiddle演示
您还可以使用pgAdmin,它提供了一个GUI来执行导入。这在这个SO线程中显示。使用pgAdmin的优点是它也适用于远程数据库。
不过,与前面的解决方案非常相似,您需要在数据库中已经有表。每个人都有自己的解决方案,但我通常在Excel中打开CSV文件,复制标题,在不同的工作表上粘贴特殊的换位,在下一列上放置相应的数据类型,然后将其复制并粘贴到文本编辑器中,并使用适当的SQL表创建查询,如下所示:
CREATE TABLE my_table (
/* Paste data from Excel here for example ... */
col_1 bigint,
col_2 bigint,
/* ... */
col_n bigint
)
DBeaver社区版(DBeaver .io)使得连接到数据库,然后导入CSV文件上传到PostgreSQL数据库变得很简单。它还可以方便地发出查询、检索数据以及将结果集下载为CSV、JSON、SQL或其他常见数据格式。
它是一个面向SQL程序员、dba和分析师的自由/开源多平台数据库工具,支持所有流行的数据库:MySQL、PostgreSQL、SQLite、Oracle、DB2、SQL Server、Sybase、MS Access、Teradata、Firebird、Hive、Presto等。对于Postgres的TOAD, SQL Server的TOAD,或者Oracle的TOAD,它是一个可行的自由/开源软件竞争对手。
I have no affiliation with DBeaver. I love the price (FREE!) and full functionality, but I wish they would open up this DBeaver/Eclipse application more and make it easy to add analytics widgets to DBeaver / Eclipse, rather than requiring users to pay for the $199 annual subscription just to create graphs and charts directly within the application. My Java coding skills are rusty and I don't feel like taking weeks to relearn how to build Eclipse widgets, (only to find that DBeaver has probably disabled the ability to add third-party widgets to the DBeaver Community Edition.)
推荐文章
- 将varchar字段的类型更改为整数:"不能自动转换为整数类型"
- PostgreSQL可以索引数组列吗?
- PostgreSQL:角色不允许登录
- 用csv模块从csv文件中读取特定的列?
- 如何查找Postgres / PostgreSQL表及其索引的磁盘大小
- 是使用各有一个模式的多个数据库更好,还是使用一个数据库有多个模式更好?
- 如果字符串包含
- 对于PostgreSQL表来说,多大才算太大?
- 将一列的多个结果行连接为一列,按另一列分组
- 使用pgadmin连接到heroku数据库
- 在PostgreSQL中快速发现表的行数
- 更改varchar列的大小为较低的长度
- 如何首次配置postgresql ?
- 数据库性能调优有哪些资源?
- 如何在PostgreSQL中自动更新时间戳