4、R软件访问mysql数据库 (1)安装及加载RODBC install.packages("RODBC") library(RODBC) 复制代码 (2)与mysql建立连接 channel=odbcConnect("mysqlodbc", uid="root", pwd="123456") 复制代码 (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 复制代码 (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 复制代码 (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 复制代码 (6)将数据框中的数据保存到数据库表中 数据框的首列没有列名,所以在保存之前需要指定列名 sqlSave(channel, USArrests, rownames = "state", addPK = TRUE) 复制代码 从以上可以看出,数据框能正确的保存到mysql数据库中去了 (7)在R软件将刚才添加到mysql数据库中的表删除掉 sqlDrop(channel,"usarrests") 复制代码 (8)关闭连接资源 odbcClose(channel) 复制代码