如何编写从CSV文件导入数据并填充表的存储过程?
当前回答
一种快速的方法是使用Python Pandas库(0.15或更高版本最好)。这将为您处理创建列的问题——尽管它为数据类型所做的选择可能不是您想要的。如果它不能完全做到你想要的,你总是可以使用生成为模板的“创建表”代码。
这里有一个简单的例子:
import pandas as pd
df = pd.read_csv('mypath.csv')
df.columns = [c.lower() for c in df.columns] # PostgreSQL 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 it 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
其他回答
看看这篇短文吧。
解决方案如下:
创建你的表:
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);
您还可以使用pgfutter,或者更好的pgcsv。
这些工具根据CSV标题为您创建表列。
pgfutter有很多bug,我推荐pgcsv。
下面是如何使用pgcsv:
sudo pip install pgcsv
pgcsv --db 'postgresql://localhost/postgres?user=postgres&password=...' my_table my_file.csv
这些都是很好的答案,但对我来说太复杂了。我只需要在postgreSQL中加载一个CSV文件,而不需要先创建一个表。
这是我的方法:
库
import pandas as pd
import os
import psycopg2 as pg
from sqlalchemy import create_engine
使用环境变量获取密码
password = os.environ.get('PSW')
创建引擎
engine = create_engine(f"postgresql+psycopg2://postgres:{password}@localhost:5432/postgres")
发动机需求分解:
Engine = create_engine(dialect+驱动程序://用户名:password@host:端口/数据库)
分解
Postgresql +psycopg2 =方言+驱动程序 Postgres =用户名 Password =来自环境变量的密码。如果需要,可以输入密码,但不建议输入 Localhost = host 5432 = port Postgres =数据库
获取您的CSV文件路径,我不得不使用编码方面。原因可以在这里找到
data = pd.read_csv(r"path, encoding= 'unicode_escape')
发送数据到Postgress SQL:
data.to_sql('test', engine, if_exists='replace')
分解
Test =你想要的表名 引擎=上面创建的引擎。也就是我们的联系 if_exists =将替换旧表。请谨慎使用。
在一起:
import pandas as pd
import os
import psycopg2 as pg
from sqlalchemy import create_engine
password = os.environ.get('PSW')
engine = create_engine(f"postgresql+psycopg2://postgres:{password}@localhost:5432/postgres")
data = pd.read_csv(r"path, encoding= 'unicode_escape')
data.to_sql('test', engine, if_exists='replace')
如果你没有权限使用COPY(在db服务器上工作),你可以使用\ 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
参见COPY的文档:
不要将COPY与psql指令\ COPY混淆。\copy调用copy FROM STDIN或copy TO STDOUT,然后在psql客户端可访问的文件中获取/存储数据。因此,当使用\copy时,文件的可访问性和访问权限取决于客户端而不是服务器。
并注意:
对于标识列,COPY FROM命令将始终写入输入数据中提供的列值,就像INSERT选项覆盖SYSTEM VALUE一样。
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中自动更新时间戳