1、下载(mysql-connector-odbc-5.3.2-win32.msi)
下载地址:http://dev.mysql.com/downloads/connector/odbc
如果下载不了的同学可以下直使用我的附件
mysql-connector-odbc-5.3.2-win32.rar (6.64 MB)
2、安装Mysql的RODBC:mysql-connector-odbc-5.3.2-win32.msi
3、配置datasource
以上Datasource配置成功
4、R软件访问mysql数据库
(1)安装及加载RODBC
- install.packages("RODBC")
- library(RODBC)
[color=rgb(51, 102, 153) !important]复制代码
(2)与mysql建立连接
- channel=odbcConnect("mysqlodbc", uid="root", pwd="123456")
[color=rgb(51, 102, 153) !important]复制代码
(3)查询该数据库下都有哪些数据库表
- > sqlTables(channel)
- TABLE_CAT TABLE_SCHEM TABLE_NAME TABLE_TYPE REMARKS
- 1 test aa TABLE
- 2 test first_table TABLE
- 3 test second_table TABLE
- 4 test students TABLE
[color=rgb(51, 102, 153) !important]复制代码
(4)查询某个表中的数据返回给数据框
- > students=sqlFetch(channel,"students")
- > students
- id name age address tel score
- 1 101 潘国远01 90 北京 2147483647 99.9
- 2 102 潘国远02 90 北京 2147483647 99.9
- 3 103 潘国远03 90 北京 2147483647 99.9
- 4 104 潘国远04 90 北京 2147483647 99.9
- 5 105 潘国远05 90 北京 2147483647 99.9
- 6 106 潘国远06 90 北京 2147483647 99.9
- 7 107 潘国远07 90 北京 2147483647 99.9
- 8 108 潘国远08 90 北京 2147483647 99.9
- 9 109 潘国远09 90 北京 2147483647 99.9
- 10 110 潘国远10 90 北京 2147483647 99.9
[color=rgb(51, 102, 153) !important]复制代码
(5)条件查询
- > sqlQuery(channel,"select name,age,address,score from students where id < 105 order by id desc")
- name age address score
- 1 潘国远04 90 北京 99.9
- 2 潘国远03 90 北京 99.9
- 3 潘国远02 90 北京 99.9
- 4 潘国远01 90 北京 99.9
[color=rgb(51, 102, 153) !important]复制代码
(6)将数据框中的数据保存到数据库表中
数据框的首列没有列名,所以在保存之前需要指定列名
- sqlSave(channel, USArrests, rownames = "state", addPK = TRUE)
[color=rgb(51, 102, 153) !important]复制代码
从以上可以看出,数据框能正确的保存到mysql数据库中去了
(7)在R软件将刚才添加到mysql数据库中的表删除掉
- sqlDrop(channel,"usarrests")
[color=rgb(51, 102, 153) !important]复制代码
(8)关闭连接资源
- odbcClose(channel)
[color=rgb(51, 102, 153) !important]复制代码