位置:首頁 > 大數據教學 > R語言教學 > R語言數據庫(MySQL)

R語言數據庫(MySQL)

數據是關係數據庫係統中存儲的統一化格式。 因此,實施我們需要非常先進和複雜的SQL查詢統計計算。但是R能夠輕鬆地連接到諸如MySql, Oracle, Sql server等多種關係數據庫並且可以從它們的記錄轉為R中的數據幀。一旦數據是在R環境中可用,就變成了正常R數據集,並可以被操縱或使用所有強大包和函數來進行分析。

在本教學中,我們將使用 MySQL 作為參考數據庫,用於連接到 R 中。

RMySQL 軟件包

R有一個名為“RMySQL”它提供了與 MySQL 數據庫之間的本地連接的內置軟件包。可以使用下麵的命令來安裝這個包到 R 的環境。

install.packages("RMySQL")

連接R到MySql

一旦軟件包安裝,我們創建 R 的連接對象連接到數據庫。這需要用戶名,密碼,數據庫名和主機名作為輸入。

# Create a connection Object to MySQL database.
# We will connect to the sampel database named "sakila" that comes with MySql installation.
 mysqlconnection = dbConnect(MySQL(), user='root', password='', dbname='sakila', host='localhost')

# List the tables available in this database.
 dbListTables(mysqlconnection)

當我們上麵的代碼執行時,它產生以下結果:

 [1] "actor"                      "actor_info"                
 [3] "address"                    "category"                  
 [5] "city"                       "country"                   
 [7] "customer"                   "customer_list"             
 [9] "film"                       "film_actor"                
[11] "film_category"              "film_list"                 
[13] "film_text"                  "inventory"                 
[15] "language"                   "nicer_but_slower_film_list"
[17] "payment"                    "rental"                    
[19] "sales_by_film_category"     "sales_by_store"            
[21] "staff"                      "staff_list"                
[23] "store"                     

查詢表

我們可以使用函數 dbSendQuery()查詢在MySQL數據庫表。查詢獲取執行在MySQL中並使用fetch()函數返回結果集。最後,它被存儲為R的數據幀。

# Query the "actor" tables to get all the rows.
result = dbSendQuery(mysqlconnection, "select * from actor")

# Store the result in a R data frame object. n=5 is used to fetch first 5 rows.
data.frame = fetch(result, n=5)
print(data.fame)

當我們上麵的代碼執行時,它產生以下結果:

  actor_id first_name    last_name         last_update
1        1   PENELOPE      GUINESS 2006-02-15 04:34:33
2        2       NICK     WAHLBERG 2006-02-15 04:34:33
3        3         ED        CHASE 2006-02-15 04:34:33
4        4   JENNIFER        DAVIS 2006-02-15 04:34:33
5        5     JOHNNY LOLLOBRIGIDA 2006-02-15 04:34:33

查詢與篩選子句

我們可以通過任何有效的 select 查詢得到結果。

result = dbSendQuery(mysqlconnection, "select * from actor where last_name='TORN'")

# Fetch all the records(with n = -1) and store it as a data frame.
data.frame = fetch(result, n=-1)
print(data)

當我們上麵的代碼執行時,它產生以下結果:

  actor_id first_name last_name         last_update
1       18        DAN      TORN 2006-02-15 04:34:33
2       94    KENNETH      TORN 2006-02-15 04:34:33
3      102     WALTER      TORN 2006-02-15 04:34:33

更新表的行

我們可以通過傳遞更新查詢到dbSendQuery()函數更新一個MySQL表中的行。

dbSendQuery(mysqlconnection, "update mtcars set disp = 168.5 where hp = 110")

在執行上麵的代碼後,我們可以看到該表在MySQL環境中已經更新。

將數據插入到表

dbSendQuery(mysqlconnection,
"insert into mtcars(row_names, mpg, cyl, disp, hp, drat, wt, qsec, vs, am, gear, carb)
values('New Mazda RX4 Wag', 21, 6, 168.5, 110, 3.9, 2.875, 17.02, 0, 1, 4, 4)"
)

執行上麵的代碼後,我們可以看到插入到表在MySQL環境的記錄行。

在MySQL中創建表

我們可以使用函數dbWriteTable()創建一個表在MySQL中。它覆蓋表,如果它已經存在,並且需要一個數據幀輸入。

# Create the connection object to the database where we want to create the table.
mysqlconnection = dbConnect(MySQL(), user='root', password='', dbname='sakila', host='localhost')

# Use the R data frame "mtcars" to create the table in MySql.
# All the rows of mtcars are taken inot MySql.
dbWriteTable(mysqlconnection, "mtcars", mtcars[, ], overwrite = TRUE)

在執行上麵的代碼後,我們可以看到在MySQL環境中有創建後的表。

在MySQL刪除表。

我們可以把 MySql 數據庫這個表刪除,通過 DROP TABLE 語句發送到 dbSendQuery(),與之前從表查詢數據的方式相同。

dbSendQuery(mysqlconnection, 'drop table if exists mtcars')

在執行上麵的代碼後,我們可以看到該表在MySQL環境被丟棄。