R语言连接MYSQL

时间:2024-01-03 11:40:32

操作系统:centos 6.4 64bit

R语言可以使用RMySQL来连接Mysql数据库,直接使用数据库里面的数据生成图像。

这个是RMYSQL的说明:

http://cran.r-project.org/web/packages/RMySQL/index.html

RMYSQL的依赖:

Depends:R (≥ 2.8.0), methods, DBI (≥ 0.2-2), utils

当然了,你得安装好mysql,至少安装mysqlclient,这个在本文就不描述了,网上很多。

根据前面的一篇R语言安装文章:http://hi.baidu.com/solohac/item/4a18e78f1bef9b5825ebd99c

我安装的是/R-3.1.0,所以只要再安装DBI就可以了。

如果你不知道版本,进入R命令行输入:version

打开R命令行,输入:

1
install.packages("DBI")

安装DBI完毕

安装RMySQL输入:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
install.packages("RMySQL")
** libs
gcc -std=gnu99 -I/usr/local/lib64/R/include -DNDEBUG -I/usr/include/mysql -I/usr/local/include    -fpic  -g -O2  -c RS-DBI.c -o RS-DBI.o
gcc -std=gnu99 -I/usr/local/lib64/R/include -DNDEBUG -I/usr/include/mysql -I/usr/local/include    -fpic  -g -O2  -c RS-MySQL.c -o RS-MySQL.o
gcc -std=gnu99 -shared -L/usr/local/lib64 -o RMySQL.so RS-DBI.o RS-MySQL.o -lmysqlclient -lz
installing to /usr/local/lib64/R/library/RMySQL/libs
** R
** inst
** preparing package for lazy loading
Creating a generic function for ‘format’ from package ‘base’ in package ‘RMySQL’
Creating a generic function for ‘print’ from package ‘base’ in package ‘RMySQL’
** help
*** installing help indices
** building package indices
** testing if installed package can be loaded
* DONE (RMySQL)
The downloaded source packages are in
‘/tmp/Rtmp1gnlCs/downloaded_packages’
Updating HTML index of packages in '.Library'
Making 'packages.html' ... done

到此,RMySQL安装完毕。

【另外】

如果你安装失败了,有如下提示:

1
2
3
4
Configuration error:
  could not find the MySQL installation include and/or library
  directories.  Manually specify the location of the MySQL
  libraries and the header files and re-run R CMD INSTALL.

则说明找不到Mysql头文件和库,需要把mysqlclient安装到这下面(我是64bit系统)

1
2
3
[root@localhost ~]# ls /usr/lib64/mysql
libmysqlclient_r.so     libmysqlclient_r.so.16.0.0  libmysqlclient.so.16      libmysqld.so    libmysqld.so.0.0.1  mysql_config
libmysqlclient_r.so.16  libmysqlclient.so           libmysqlclient.so.16.0.0  libmysqld.so.0  mysqlbug            plugin

下面演示RMySQL的使用(当然,数据库你得自己建,数据你得自己生成):

1
2
3
4
5
6
7
8
> library(RMySQL)
Loading required package: DBI
>
> mysql<-dbConnect(MySQL(), dbname="yourdbname", username="root", password="solohac"  )
> count<-dbGetQuery(mysql, "select count(*) from logs")
> count
  count(*)
1     4676