R MySQL Connection
MySQL is the most popular relational database management system. In terms of WEB applications, MySQL is one of the best RDBMS (Relational Database Management System) applications.
If you are not yet familiar with MySQL, you can refer to:MySQL Tutorial
Reading and writing MySQL files in R requires installing an extension package. We can install it by entering the following command in the R console:
install.packages("RMySQL", repos = "https://mirrors.ustc.edu.cn/CRAN/")
Check whether it was installed successfully:
> any(grepl("RMySQL",installed.packages()))
[1] TRUE
MySQL has now been acquired by Oracle, so many people use its replica, MariaDB. MariaDB is open source under the GNU GPL, and its development is led by some of MySQL's original developers, so the syntax and operations are largely similar:
install.packages("RMariaDB", repos = "https://mirrors.ustc.edu.cn/CRAN/")
Create the table runoob in the test database; the table structure and data code are as follows:
Example
-- -- Table structure runoob
--
CREATE
TABLE
`
runoob
`
(
`
id
`
int
(
11
)
NOT
NULL
,
`
name
`
char
(
20
)
NOT
NULL
,
`
url
`
varchar
(
255
)
NOT
NULL
,
`
likes
`
int
(
11
)
NOT
NULL
)
ENGINE
=
InnoDB
DEFAULT
CHARSET
=
utf8mb4
;
-- -- Dumping data for table runoob
--
INSERT
INTO
`
runoob
`
(
`
id
`
,
`
name
`
,
`
url
`
,
`
likes
`
)
VALUES
(
1
,
'
'
,
'
www.google.com
'
,
111
)
,
(
2
,
'
Runoob
'
,
'
www.runoob.com
'
,
222
)
,
(
3
,
'
Taobao
'
,
'
www.taobao.com
'
,
333
)
;
Next, we can use the RMySQL package to read the data:
Example
library
(
RMySQL
)
dbname is the database name; fill in the parameters here according to your own situation
mysqlconnection
=
dbConnect
(
MySQL
(
)
, user
=
'root'
, password
=
''
, dbname
=
'test'
,host
=
'localhost'
)
View data
dbListTables
(
mysqlconnection
)
Next, we can use dbSendQuery to read a table from the database, and retrieve the result set with the fetch() function:
Example
library
(
RMySQL
)
Query the sites table; create, read, update, and delete operations can be implemented through the SQL statement in the second argument
result
=
dbSendQuery
(
mysqlconnection,
"select * from sites"
)
Retrieve the first two rows of data
data.frame
=
fetch
(
result, n
=
2
)
(
data.frame
)