2016-10-06 7 views
1

私はテーブルmyschema.fruitsをpostgresqlデータベースmydatabaseに持っています。 Rスクリプトの中から、そのスクリプトの最後にそのテーブルに1行を挿入したいと思います。テーブル行には、3列のtype,tasteおよびcolorがあります。私はそうのように同じ変数名と私のRスクリプトの3つの異なる変数で持っているものである:Rからpostgresqlテーブルに1行のデータを書き込むにはどうすればよいですか?

type <- "Apple" 
taste <- "Sweet" 
color <- "Red" 

私はこの挿入を実行するためにRPostgreSQL driverを使用したいが、私はそれを行う方法を見つけ出すことはできませんか?

答えて

1

必要に応じて、ホスト、ポート、ユーザーを変更してパスワードを追加してください。

最初のオプション:テーブルにデータフレームを付加

dt2insert = data.frame(type = "Apple", 
         taste = "Sweet", 
         color = "Red", 
         stringsAsFactors = FALSE) 
con = dbConnect(dbDriver("PostgreSQL"),dbname = "mydatabase", 
       host = "localhost", port = 5432, 
       user = "postgres") 
dbWriteTable(con, name = c("myschema","fruits"), value = dt2insert,append=TRUE,row.names=FALSE,overwrite=FALSE) 
dbDisconnect(con) 

番目のオプション:コマンドINTO INSERTを使用して、別の方法としてコマンド

type <- "Apple" 
taste <- "Sweet" 
color <- "Red" 
qry = paste0("INSERT INTO myschema.fruits VALUES ('",type,"','",taste,"','",color,"');") 

con = dbConnect(dbDriver("PostgreSQL"),dbname = "mydatabase", 
       host = "localhost", port = 5432, 
       user = "postgres") 
dbSendQuery(con,qry) 
dbDisconnect(con) 
0

INTO INSERTを使用してクエリのパラメータ化を可能にする低レベルのpostgresqlExecStatement関数の使用を検討してください。これの主な利点は、適切なデータ型のクエリ文字列を手動で作成する必要がないことです。この場合は、追加の引用符を省略することができます。'

type <- "Apple" 
taste <- "Sweet" 
color <- "Red" 

con = dbConnect(dbDriver("PostgreSQL"),dbname = "mydatabase", 
       host = "localhost", port = 5432, 
       user = "postgres") 
tmp <- postgresqlExecStatement(con, 
       'insert into myschema.fruits VALUES ($1, $2, $3)', 
       list(type, taste, color)) 
dbClearResult(tmp) 
dbDisconnect(con) 
関連する問題