无法通过Putty连接R和PostgreSQL

时间:2015-06-25 10:07:45

标签: r postgresql

我遇到集成PostgreSQL和R的问题 我总是将SQL查询的输出卸载到.txt文件中,然后使用read.table()函数将em下载到R中。 但现在我需要直接在R中获取查询的输出。 我对SQL的了解?它是PostgreSQL,我使用PuttY连接到db 我也知道PuttY关于我的连接的信息

  1. 主机名(或IP地址)
  2. 端口
  3. 已保存的会话=' dbcenter'
  4. ConnectionType = SSH
  5. key - 扩展名为.ppk的文件
  6. 此密钥的密码
  7. 此外,在编写查询之前,我在打开的窗口中选择

    1. 区域
    2. 数据库
    3. 这是我对putty了解的完整信息,我不知道如何直接在R脚本中编写查询。我试过RPostgreSQL包,没有成功。

      有人能帮助我吗?

1 个答案:

答案 0 :(得分:0)

Firstly, make sure you can connect to the remote DB without R, for example, using pgadmin3 or psql (see this link1 and link2 for more idea about pgadmin/psql/remote/port forwarding). Then, try along these lines: dbname <- "myname"; dbuser <- "myname"; dbpass <- "IWillNotTell"; dbhost <- "remotehostname"; dbport <- 5432; If the remote host is withing the same local network (ie, your local host is myhost.host.edu), then, the following should work as well: dbhost <- "remote" library(RPostgreSQL) drv <- dbDriver("PostgreSQL") con <- dbConnect(drv, host=dbhost, port=dbport, dbname=dbname, user=dbuser, password=dbpass) query = 'SELECT * FROM TABLENAME' dbGetQuery(con, query) sqldata<-dbGetQuery(con, query) summary(sqldata) sqldata will be a dataframe The important thing is firewall and access to the DB. I suggest, using pgadmin3 to make sure you can connect to the server. If the local firewall does not allow connection to the postgresql server port then you'll need to use ssh tunneling - the connection can get pretty slow depending on how remote the remote host is. For example: assuming the sever allows listens to only "localhost" (this is wrt to the server), then: ssh -L 22222:localhost:5432 myname@remotehostname will forward the 22222 port on your client to the remote's 5432 port. Again, use pgadmin3 at this point to make that you can connect. Then set dbhost <- "localhost"; dbport <- "22222" and use the same dbConnect call. Once the dbConnect call is successfull all sql results will be in R local