一、下载安装ODBC
根据自己系统版本下载安装对应的版本;
下载地址:http://dev.mysql.com/downloads/connector/odbc

二、配置ODBC
windows:控制面板⇒⇒管理工具⇒⇒ODBC 数据源(64 位)⇒⇒添加⇒⇒选中mysql ODBC driver一项
- data source name 一项填入你要使用的名字,自己随便命名,例如:MySQL;
- description一项随意填写,例如MyWorld;
- TCP/IP Server 填写服务器IP,本地为:127.0.0.1;
- user 填写你的mysql用户名;
- password 填写你的mysql密码;
- 然后数据库里会出现你的mysql里的所有数据库(我这里选world),选择一个数据库,OK。 
三、使用R连接及操作数据库MySQL
1、连接数据库
> # 加载包RODBC
> library(RODBC)
> # 连接MySQL数据库
> channel <- odbcConnect("MySQL", uid="root", pwd="root")
2、查看数据库所有表
> sqlTables(channel)
  TABLE_CAT TABLE_SCHEM      TABLE_NAME TABLE_TYPE REMARKS
1     world                        city      TABLE        
2     world                     country      TABLE        
3     world             countrylanguage      TABLE     
3、查询表的数据
> data <- sqlFetch(channel,"city")
> head(data)
  ID           Name CountryCode      District Population
1  1          Kabul         AFG         Kabol    1780000
2  2       Qandahar         AFG      Qandahar     237500
3  3          Herat         AFG         Herat     186800
4  4 Mazar-e-Sharif         AFG         Balkh     127800
5  5      Amsterdam         NLD Noord-Holland     731200
6  6      Rotterdam         NLD  Zuid-Holland     593321
4、使用SQL语句查询
> # 查询Population大于等于500万的人名,并按ID降序排序
> sql = "select ID,Name,Population from city where Population >= 5000000 order by id desc"
> sqlQuery(channel,sql)
     ID                Name Population
1  3793            New York    8008278
2  3580              Moscow    8389200
3  3357            Istanbul    8787958
4  3320             Bangkok    6320174
5  2890                Lima    6464693
6  2823              Lahore    5063499
...
5、使用R将数据表添加到数据库
> head(iris)
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6         3.1          1.5         0.2  setosa
5          5.0         3.6          1.4         0.2  setosa
6          5.4         3.9          1.7         0.4  setosa
> # 由于数据框没有行名,所以保存到数据库中时需要指定一个行名(比如这里是“id”)
> sqlSave(channel, iris, rownames = "id", addPK = TRUE)
打开cmd进入到mysql,执行下列语句可以看到iris数据已经添加到MySQL数据库;
mysql>>> use world;
mysql>>> show tables;
mysql>>> select * from iris;


6、使用R语言删除数据库中的表
> sqlDrop(channel,"iris") # 删除表数据库中的iris
7、关闭数据库的连接
> odbcClose(channel)