1、下载mysql-connector-odbc,并安装
2、windows:控制面板->管理工具->数据源(ODBC)
->ODBC数据管理器->系统DSN->添加->MySQL ODBC Driver
->data source name(如:mysql_data)
description
TCP/IP Server(服务器IP)
port(如:3306)
user
password
database
test(显示连接成功)
->在“系统数据源”中显示“名称”,“驱动程序”
3、在R界面
3.1、程序包->安装程序包->RODBC
3.2、library(RODBC)
3.3、查看可用的数据源
> odbcDataSources()
dBASE Files Excel Files
"Microsoft Access dBASE Driver (*.dbf, *.ndx, *.mdx)" "Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)"
MS Access Database MySQL
"Microsoft Access Driver (*.mdb, *.accdb)" "MySQL ODBC 5.3 ANSI Driver"
mysql_data
"MySQL ODBC 5.3 ANSI Driver"
3.4、data_table <- odbcConnect("mysql_data", uid="root", pwd="123")
> data_table
RODBC Connection 1
Details:
case=tolower
DSN=mysql_data
UID=root
PWD=******
3.5、 查看数据库中的表
> sqlTables(data_table)
TABLE_CAT TABLE_SCHEM TABLE_NAME TABLE_TYPE REMARKS
1 sakila actor TABLE
2 sakila actor_info VIEW VIEW
3 sakila address TABLE
4 sakila category TABLE
5 sakila city TABLE
6 sakila country TABLE
7 sakila customer TABLE
3.6、查看表的内容,存到数据框里
> data_country<-sqlFetch(data_table,"country")
> data_country
country_id country last_update
1 7 Armenia 2006-02-15 04:44:00
2 8 Australia 2006-02-15 04:44:00
3 9 Austria 2006-02-15 04:44:00
4 23 China 2006-02-15 04:44:00
3.7、SQL查询
> sql_country<-sqlQuery(data_table,"select country_id,country,last_update from country where country_id<5 order by country")
> sql_country
country_id country last_update
1 1 Afghanistan 2006-02-15 04:44:00
2 2 Algeria 2006-02-15 04:44:00
3 3 American Samoa 2006-02-15 04:44:00
4 4 Angola 2006-02-15 04:44:00
3.8、
head函数获取前n条记录
> head(data_country,n=5)
country_id country last_update
1 1 Afghanistan 2006-02-15 04:44:00
2 2 Algeria 2006-02-15 04:44:00
3 3 American Samoa 2006-02-15 04:44:00
4 4 Angola 2006-02-15 04:44:00
5 5 Anguilla 2006-02-15 04:44:00
head函数获取后n条记录
> tail(data_country,n=4)
country_id country last_update
106 106 Virgin Islands, U.S. 2006-02-15 04:44:00
107 107 Yemen 2006-02-15 04:44:00
108 108 Yugoslavia 2006-02-15 04:44:00
109 109 Zambia 2006-02-15 04:44:00
3.9、关闭R与数据库的连接
> odbcClose(data_table)
原文:http://www.cnblogs.com/wwxbi/p/4338506.html