简体   繁体   English

将PostgreSQL本地文件分块读取到R中并导出到.csv

[英]Read a PostgreSQL local file into R in chunks and export to .csv

I have a local file in PostgreSQL format that I would like to read into R into chunks and export it as .csv . 我有一个PostgreSQL格式的本地文件,我想将其读入R块中并将其导出为.csv

I know this might be a simple question but I'm not at all familiar with PostgreSQL or SQL . 我知道这可能是一个简单的问题,但是我对PostgreSQLSQL都不熟悉。 I've tried different things using R libraries like RPostgreSQL , RSQLite and sqldf but I couldn't get my head around this. 我已经尝试过使用R库(例如RPostgreSQLRSQLitesqldf但我RSQLite sqldf

If your final goal is to create a csv file, you can do it directly using PostgreSQL. 如果您的最终目标是创建一个csv文件,则可以直接使用PostgreSQL完成。

You can run something similar to this: COPY my_table TO 'C:\\my_table.csv' DELIMITER ',' CSV HEADER; 您可以运行类似于以下内容:将my_table复制到'C:\\ my_table.csv'DELIMITER',CSV HEADER;

Sorry if I misunderstood your requirement. 抱歉,如果我误解了您的要求。

The requirement is to programmatically create a very large .csv file from scratch and populate it from data in a database? 要求是从头开始以编程方式创建一个非常大的.csv文件,并从数据库中的数据填充它。 I would use this approach. 我会使用这种方法。

Step 1 - isolate the database data into a single table with an auto incrementing primary key field. 第1步-使用自动递增的主键字段将数据库数据隔离到单个表中。 Whether you always use the same table or create and drop one each time depends on the possibility of concurrent use of the program. 是否总是使用同一张表还是每次创建和删除一张表都取决于并发使用该程序的可能性。

Step 2 - create the .csv file with your programming code. 第2步-使用您的编程代码创建.csv文件。 It can either be empty, or have column headers, depending on whether or not you need column headers. 它可以为空,也可以具有列标题,具体取决于您是否需要列标题。

Step 3 - get the minimum and maximum primary key values from your table. 第3步-从表中获取最小和最大主键值。

Step 4 - set up a loop in your programming code using the values from Step 3. Inside the loop: 第4步-使用第3步中的值在您的编程代码中建立一个循环。在循环内:

  • query the table to get x rows 查询表以获取x行
  • append those rows to your file 将这些行附加到文件中
  • increment the variables that control your loop 增加控制循环的变量

Step 5 - Do whatever you have to do with the file. 第5步-对该文件进行任何处理。 Don't try to read it with your programming code. 不要尝试与您的编程代码一起阅读它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM