R MySQL Connection
MySQL is the most popular relational database management system. In WEB applications, MySQL is one of the best RDBMS (Relational Database Management System) application software.
If you are not familiar with MySQL, you can refer to:MySQL Tutorial
R language reading and writing MySQL files requires installing an extension package. We can enter the following command in the R console to install it:
install.packages("RMySQL", repos = "https://mirrors.ustc.edu.cn/CRAN/")
To check whether the installation is successful:
> any(grepl("RMySQL",installed.packages()))
[1] TRUE
MySQL is currently acquired by Oracle, so many people use its fork MariaDB. MariaDB is open source under GNU GPL. The development of MariaDB is led by some of the original developers of MySQL, so the syntax and operations are similar:
install.packages("RMariaDB", repos = "https://mirrors.ustc.edu.cn/CRAN/")
Create the data table example in the test database. The table structure and data code are as follows:
Example
Next we can use the RMySQL package to read the data:
Example
# dbname is the database name, please fill in the parameters here according to your actual situation
mysqlconnection = dbConnect(MySQL(), user = 'root', password = '', dbname = 'test',host = 'localhost')
# View data
dbListTables(mysqlconnection)
Next we can use dbSendQuery to read the database table, and the result set is obtained through the fetch() function:
Example
# Query the sites table. CRUD operations can be implemented through the SQL statement of the second parameter
result = dbSendQuery(mysqlconnection, "select * from sites")
# Get the first two rows of data
data.frame = fetch(result, n = 2)
print(data.frame)