LoginSignup
3
3

More than 3 years have passed since last update.

R言語でSQLite

Posted at

Rで.dbを吐き出す必要があるときに。

RからSQLiteで

library("RSQLite")

con = dbConnect(SQLite(), "pp.db", synchronous="off")
#指定した名前の.dbにつなぐ。なければ作る。

dbSendQuery(con, "create table hoge(hinmei text, nedan int)")
#テーブルをつくる。なければはじかれる

dbListTables(con)
dbListFields(con, "hoge")
#テーブルがあることを確認。デーブルの定義がされていることを確認。

dbSendQuery(con, "insert into hoge values('りんご', 500)")
dbSendQuery(con, "insert into hoge values('みかん', 300)")
dbGetQuery(con, "select * from hoge")
#送ったものが入っているか確認
dbSendQuery(con, "update hoge set nedan=200 where hinmei='みかん'")
#中の値をupdateしてみる
dbGetQuery(con, "select * from hoge")
dbReadTable(con, "hoge")
#中にはいっているか確認

一行ずつ送るのでなく、Rで作成したデータフレームをそのままテーブルに入れる

#一気にデータをテーブルにいれてしまう
dbWriteTable(con, "arrests", USArrests)
dbReadTable(con, "arrests")
#確認
dbGetQuery(con, "select * from arrests limit 3")

dbListTables(con)
dbDisconnect(con)
#接続終了

以上

ドキュメントはこちら

#https://www.rdocumentation.org/packages/RSQLite/versions/0.11.4/topics/dbSendQuery-methods
3
3
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
3
3