LoginSignup
10
10

More than 5 years have passed since last update.

RでPostgreSQLにつなぐ

Posted at
> install.packages('RPostgreSQL')
> library(RPostgreSQL)
> con <- dbConnect(PostgreSQL(), host="localhost", > port=5432, user= "postgres", password="*****", dbname="db_name")
> dbListTables(con)  # テーブル一覧取得
> dbListFields(con, "users")  # usersテーブルのカラム名一覧取得

クエリを実行してデータフレームを得る

R
> con <- dbConnect(PostgreSQL(), host="localhost", port=5432, user="aikawa", password="", dbname="wantedly")
> light_query <- "SELECT * FROM users LIMIT 4"
> data <- dbGetQeury(con, light_query)
> heavy_query <- "SELECT * FROM users"
> rs <- dbSendQuery(con, heavy_query)
> summary(rs)
<PostgreSQLResult:(10272,0,11)> 
  Statement: SELECT * FROM users 
  Has completed? no 
  Affected rows: -1 
  Rows fetched: 0 
> data <- fetch(rs)
> nrow(data)  # 全体はもっと多いのに500行しか取得しない
[1] 500
>  summary(rs)  # summaryはrow fetchedが500になっている
<PostgreSQLResult:(10272,0,11)> 
  Statement: SELECT * FROM users 
  Has completed? no 
  Affected rows: -1 
  Rows fetched: 500 
> data <- fetch(rs)  # 次の500件を取得
> data <- fetch(rs, n=1000)  # 次の1000件, n=-1で全て取得

エラー処理

dbSendQueryでの結果を取得しfetchすべて仕切らないまま(dbHasCompleted(rs)FALSEのまま)、dbSendQueryなどのクエリを実行すると

R
 Error in postgresqlExecStatement(conn, statement, ...) : 
  RS-DBI driver: (connection with pending rows, close resultSet before continuing)

このようなものがでた場合、

R
dbClearResult(rs)

もしくは、rsなど変数に入れなかった場合は、

R
dbClearResult(dbListResults(con)[[1]])

とすれば、改めてクエリを実行できるようになる

REF

10
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
10