简体   繁体   English

如何将数据从 PostgreSQL 数据库导入 R?

[英]How to import data from PostgreSQL database to R?

I'm thinking of importing data from database directly into r using RPostgresQL package.我正在考虑使用RPostgresQL包将数据从数据库直接导入到 r 中。 So far, I used to write queries in Postico (a PostgreSQL client) software and export as csv and then import the csv file into R.到目前为止,我曾经在Postico (一个 PostgreSQL 客户端)软件中编写查询并导出为 csv,然后将 csv 文件导入到 R 中。
This is what I've written so far and no clue how to proceed next.这是我到目前为止所写的,不知道下一步如何进行。

library('RPostgreSQL')
pg=dbDriver("PostgreSQL")
con = dbConnect(pg, user="msahil515", password="",
            host="localhost", port=5432, dbname="msahil515")

How do I load tables from the database into R after this or how to write queries in R to extract only necessary data from database?在此之后如何将数据库中的表加载到 R 中,或者如何在 R 中编写查询以仅从数据库中提取必要的数据?

Here is a straight answer to your question.这是您问题的直接答案。 This definitely can be extended这绝对可以扩展

library('RPostgreSQL')

#create connection object
con <- dbConnect(drv =PostgreSQL(), 
                 user="msahil515", 
                 password="",
                 host="localhost", 
                 port=5432, 
                 dbname="msahil515")

dbListTables(con)   #list all the tables 

#query the database and store the data in datafame
first_results <- dbGetQuery(con, "SELECT * from FOO limit 10;")

dbDisconnect(con)   #disconnect from database

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

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