登录
首页精彩阅读R语言数据库(MySQL)
R语言数据库(MySQL)
2017-06-19
收藏

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环境被丢弃。


数据分析咨询请扫描二维码

客服在线
立即咨询