R语言 连接数据库
数据库是一个有组织的信息的集合,以便可以轻松地访问它。它可以被访问或存储在计算机系统中。它可以通过数据库管理系统(DBMS)来管理,它是一种用于管理数据的软件。数据库指的是以结构化形式存在的相关数据。
它支持数据的存储和操作。基本上,一个数据库有5种子语言。
- 数据定义语言(DDL)
- 数据查询语言(DQL)
- 数据操作语言(DML)
- 数据控制语言(DCL)
- 事务控制语言(TCL)
为了用R编程连接数据库,我们将把R脚本与MySQL数据库连接起来。
要安装MYSql,请参考其官方网站dev.mysql.com。
要开始连接过程,请按照下面的步骤进行。
第1步: 用以下命令在MySQL中创建一个数据库。
create database databasename;
正如你所看到的,在这张图片中,我们使用了命令来访问数据库,而且在数据库中进行了DML操作。
第2步: 为了将数据库与R连接起来,我们可以使用R Studio。要下载R Studio,请访问rstudio.com
第3步: 使用以下命令在RStudio中安装MySQL库。
install.packages("RMySQL")
现在以RScript的形式执行以下命令。
#To check whether the library is installed or not
library(RMySQL)
# Create a connection Object to MySQL database.
mysqlconnection = dbConnect(MySQL(), user = 'root',
password = 'root',
dbname = 'onlinetutorials', host = 'localhost')
typeof(mys)
# List the tables available in this database.
dbListTables(mysqlconnection)
# Query the "actor" tables to get all the rows.
a = dbSendQuery(mysqlconnection,
"create table students(id int, name varchar(10))")
a = dbSendQuery(mysqlconnection,
"insert into students values(101, 'amit')")
a = dbSendQuery(mysqlconnection,
"insert into students values(102, 'aman')")
result = dbSendQuery(mysqlconnection,
"select * from students")
# Store the result in a R data frame object.
# n = 5 is used to fetch first 5 rows.
data.frame = fetch(result)
print(data.frame)
输出