如何通过RPostgreSQL执行SQL查询文件 [英] How to execute sql query files via RPostgreSQL

查看:132
本文介绍了如何通过RPostgreSQL执行SQL查询文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 RPostgreSQL 包通过R访问我的PostgreSQL数据库(9.3)。
我有一些非常长且很大的sql查询(从raster2pgsql生成几个MB。)。

I am accessing my PostgreSQL database (9.3) via R using the RPostgreSQL package. I have a few very long and big sql queries (several MB big. generated from raster2pgsql).

如何发送/执行sql查询文件是否作为R中的语句?

正常方式

\i query.sql

似乎无法通过 dbSendQuery工作
我试图通过 readLines 作为字符向量读取整个sql文件,但是这也失败了,因为dbSendQuery显然仅支持单个命令?

does not seem to work via dbSendQuery. I tried to read in the whole sql file as character vector via readLines, however this also fails, because dbSendQuery only supports a single command apparently?

推荐答案

dbSendQuery dbGetQuery 仅用于 SQL部分,而不是psql命令,例如 \i

在您的情况下,实际上最简单的方法是使用 readLines ,然后在 sapply 调用中包装 dbGetQuery

dbSendQuery or dbGetQuery is just for the "SQL" part, not the psql commands such as \i.
In your case the simplest is indeed to use readLines but then wrap dbGetQuery in a sapply call.

con <- dbConnect(...)          #Fill this as usual
queries <- readLines("query.sql")
sapply(queries, function(x) dbGetQuery(con,x))
dbDisconnect(con)

由于我经常使用它,因此在我的 .Rprofile 文件中有一个快捷方式:

Since I use this very often, I have a shortcut for this in my .Rprofile file:

dbGetQueries<-function(con,queries)sapply(queries,function(x)dbGetQuery(con,x))

当然,您也可以使用 s ystem 方式:

Of course, you can also go the system way:

system("psql -U username -d database -h 127.0.0.1 -p 5432 -f query.sql") #Remember to use your actual username, database, host and port

这篇关于如何通过RPostgreSQL执行SQL查询文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆