R語言學習筆記(五):資料庫

Yanwei Liu
4 min readNov 25, 2019

--

# 安裝 RSQLite 與 DBI 套件pkgs <- c("RSQLite", "DBI")
install.packages(pkgs)

常用的 DBI 套件函數

  • dbConnect() 函數:建立與資料庫的連結,多數的 DBI 套件函數會以 conn 參照這個函數所輸出的物件
  • dbDisconnect() 函數:中斷與資料庫的連結
  • dbWriteTable() 函數:創建資料庫表格
  • dbExecute() 函數:執行資料庫的指令並回傳受影響的觀測值個數
  • dbListFields() 函數:列出指定表格的欄位名稱
  • dbReadTable() 函數:讀取整張資料庫表格
  • dbGetQuery() 函數:執行查詢資料庫指令
  • dbRemoveTable() 函數:刪除整張資料庫表格

建立資料庫

#在桌面建立demo.dblibrary(DBI)
library(gapminder)
user_desktop <- "C:/Users/Administrator/Desktop/"
db_path <- paste0(user_desktop, "demo.db")
con <- dbConnect(RSQLite::SQLite(), dbname = db_path)
dbListTables(con) #列出資料庫中的資料
dbWriteTable(con, name = "gapminder", value = gapminder) #寫入
dbListTables(con) #列出
dbDisconnect(con) #取消連接

建立(C)並讀取(R)表格中的資料

dbWriteTable(con, name = "gapminder", value = gapminder)#create_statement和insert_statement中都是SQL指令
create_statement <- "
CREATE TABLE cities (
city TEXT NOT NULL,
country TEXT NOT NULL
);"
insert_statement <- "INSERT INTO cities (city, country) VALUES ('Taipei', 'Taiwan'), ('Boston', 'United States'), ('Tokyo', 'Japan');"dbExecute(con, statement = create_statement) #執行SQL指令(C)
dbExecute(con, statement = insert_statement) #執行SQL指令(C)
dbListTables(con) #列出con(R)
dbReadTable(con, "cities") #讀取con中的cities(R)
#透過dbGetQuery直接執行SQL指令進行查詢(R)dbGetQuery(con, statement = "SELECT * FROM gapminder WHERE country = 'Taiwan';")

更新(U)並刪除(D)表格中的資料

#更新指令(U)update_statement <- "UPDATE cities SET city = 'New York' WHERE city = 'Boston';"#執行更新指令(U)dbExecute(con, statement = update_statement)dbReadTable(con, name = "cities")#刪除指令(D)delete_statement <- "DELETE FROM cities WHERE city = 'London';"#執行刪除指令(D)dbExecute(con, statement = delete_statement)dbReadTable(con, name = "cities")

--

--

No responses yet