R語言連接數(shù)據(jù)庫(MySQL)

關(guān)系數(shù)據(jù)庫系統(tǒng)中的數(shù)據(jù)是以規(guī)范化格式存儲(chǔ)的。 所以,為了進(jìn)行統(tǒng)計(jì)計(jì)算凯旋,我們需要非常高級(jí)和復(fù)雜的SQL查詢。但是R可以很容易地連接到許多關(guān)系數(shù)據(jù)庫钉迷,如:MySQL至非,Oracle,Sql Server等糠聪,并將它們作為數(shù)據(jù)幀提取荒椭。 當(dāng)從數(shù)據(jù)庫中讀取數(shù)據(jù)到R環(huán)境中可用以后,它就成為一個(gè)正常的R數(shù)據(jù)集舰蟆,可以使用所有強(qiáng)大的軟件包和函數(shù)進(jìn)行操作或分析趣惠。

在本教程中,我們將使用R編程語言連接到MySQL數(shù)據(jù)庫身害。

RMySQL包

R有一個(gè)名為RMySQL的內(nèi)置包味悄,它提供與MySql數(shù)據(jù)庫之間的本機(jī)連接。您可以使用以下命令在R環(huán)境中安裝此軟件包题造。

install.packages("RMySQL")

將R連接到MySql

當(dāng)安裝了軟件包(RMySQL)之后傍菇,我們?cè)赗中創(chuàng)建一個(gè)連接對(duì)象以連接到數(shù)據(jù)庫。它需要用戶名界赔,密碼丢习,數(shù)據(jù)庫名稱和主機(jī)名等數(shù)據(jù)庫連接所需要的信息。

library("RMySQL");
# Create a connection Object to MySQL database.
# We will connect to the sampel database named "testdb" that comes with MySql installation.
mysqlconnection = dbConnect(MySQL(), user = 'root', password = '123456', dbname = 'testdb',
   host = 'localhost')

# List the tables available in this database.
dbListTables(mysqlconnection)

當(dāng)我們執(zhí)行上述代碼時(shí)淮悼,會(huì)產(chǎn)生以下結(jié)果(當(dāng)前數(shù)據(jù)中的所有表) -

 [1] "articles"       "contacts"       "demos"          "divisions"     
 [5] "items"          "luxuryitems"    "order"          "persons"       
 [9] "posts"          "revenues"       "special_isnull" "t"             
[13] "tbl"            "tmp"            "v1"             "vparts"  

查詢表

可以使用dbSendQuery()函數(shù)查詢MySQL中的數(shù)據(jù)庫表咐低。該查詢?cè)贛ySql中執(zhí)行,并使用R 的fetch()函數(shù)返回結(jié)果集,最后將此結(jié)果作為數(shù)據(jù)幀存儲(chǔ)在R中袜腥。

假設(shè)要查詢的表是:persons见擦,其創(chuàng)建語句和數(shù)據(jù)如下 -

/*
Navicat MySQL Data Transfer

Source Server         : localhost-57
Source Server Version : 50709
Source Host           : localhost:3306
Source Database       : testdb

Target Server Type    : MYSQL
Target Server Version : 50709
File Encoding         : 65001

Date: 2017-08-24 00:35:17
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `persons`
-- ----------------------------
DROP TABLE IF EXISTS `persons`;
CREATE TABLE `persons` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `full_name` varchar(255) NOT NULL,
  `date_of_birth` date NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of persons
-- ----------------------------
INSERT INTO `persons` VALUES ('1', 'John Doe', '1990-01-01');
INSERT INTO `persons` VALUES ('2', 'David Taylor', '1989-06-06');
INSERT INTO `persons` VALUES ('3', 'Peter Drucker', '1988-03-02');
INSERT INTO `persons` VALUES ('4', 'Lily Minsu', '1992-05-05');
INSERT INTO `persons` VALUES ('5', 'Mary William', '1995-12-01');

將上述表導(dǎo)入到數(shù)據(jù)庫中钉汗,并創(chuàng)建以下R代碼,用來執(zhí)行從數(shù)據(jù)庫的表中查詢數(shù)據(jù) -

library("RMySQL");
# Create a connection Object to MySQL database.
# We will connect to the sampel database named "testdb" that comes with MySql installation.
mysqlconnection = dbConnect(MySQL(), user = 'root', password = '123456', dbname = 'testdb',
   host = 'localhost');
# Query the "actor" tables to get all the rows.
result = dbSendQuery(mysqlconnection, "select * from persons")

# Store the result in a R data frame object. n = 5 is used to fetch first 5 rows.
data.frame = fetch(result, n = 5)
print(data.frame)

執(zhí)行上面示例代碼鲤屡,得到以下結(jié)果 -

  id     full_name date_of_birth
1  1      John Doe    1990-01-01
2  2  David Taylor    1989-06-06
3  3 Peter Drucker    1988-03-02
4  4    Lily Minsu    1992-05-05
5  5  Mary William    1995-12-01

使用過濾子句查詢

我們可以傳遞任何有效的選擇查詢來獲取結(jié)果损痰,如下代碼所示 -

library("RMySQL");
# Create a connection Object to MySQL database.
# We will connect to the sampel database named "testdb" that comes with MySql installation.
mysqlconnection = dbConnect(MySQL(), user = 'root', password = '123456', dbname = 'testdb',
   host = 'localhost');
result = dbSendQuery(mysqlconnection, "select * from persons where date_of_birth = '1990-01-01'")

# Fetch all the records(with n = -1) and store it as a data frame.
data.frame = fetch(result, n = -1)
print(data.frame)

當(dāng)我們執(zhí)行上述代碼時(shí),會(huì)產(chǎn)生以下結(jié)果 -

  id full_name date_of_birth
1  1  John Doe    1990-01-01

更新表中的行記錄

可以通過將更新查詢傳遞給dbSendQuery()函數(shù)來更新MySQL表中的行酒来。

dbSendQuery(mysqlconnection, "update persons set date_of_birth = '1999-01-01' where id=3")

執(zhí)行上述代碼后卢未,可以看到在MySql已經(jīng)更新persons表中對(duì)應(yīng)的記錄。

將數(shù)據(jù)插入到表中

參考以下代碼實(shí)現(xiàn) -

library("RMySQL");
# Create a connection Object to MySQL database.
# We will connect to the sampel database named "testdb" that comes with MySql installation.
mysqlconnection = dbConnect(MySQL(), user = 'root', password = '123456', dbname = 'testdb',
   host = 'localhost');
dbSendQuery(mysqlconnection,
   "insert into persons(full_name, date_of_birth) values ('Maxsu', '1992-01-01')"
)

執(zhí)行上述代碼后堰汉,可以看到向MySql的persons表中辽社,插入一行數(shù)據(jù)。

在MySql中創(chuàng)建表

我們通過使用dbWriteTable()函數(shù)向MySql中創(chuàng)建表翘鸭。它會(huì)覆蓋表滴铅,如果它已經(jīng)存在并且以數(shù)據(jù)幀為輸入。

library("RMySQL");
# Create the connection object to the testdb database where we want to create the table.
mysqlconnection = dbConnect(MySQL(), user = 'root', password = '123456', dbname = 'testdb',host = 'localhost')

# Use the R data frame "mtcars" to create the table in MySql.
# All the rows of mtcars are taken inot MySql.
dbWriteTable(mysqlconnection, "mtcars", mtcars[, ], overwrite = TRUE)

執(zhí)行上述代碼后就乓,我們可以看到在MySql數(shù)據(jù)庫中創(chuàng)建一個(gè)名稱為:mtcars的表汉匙,并有填充了一些數(shù)據(jù)。

在MySql中刪除表

我們可以刪除MySql數(shù)據(jù)庫中的表生蚁,將drop table語句傳遞到dbSendQuery()函數(shù)中盹兢,就像在SQL中查詢表中的數(shù)據(jù)一樣。

dbSendQuery(mysqlconnection, 'drop table if exists mtcars')

執(zhí)行上述代碼后守伸,我們可以看到MySql數(shù)據(jù)庫中的mtcars表被刪除绎秒。

出處:http://www.yiibai.com/r/r_database.html

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市尼摹,隨后出現(xiàn)的幾起案子见芹,更是在濱河造成了極大的恐慌,老刑警劉巖蠢涝,帶你破解...
    沈念sama閱讀 216,591評(píng)論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件玄呛,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡和二,警方通過查閱死者的電腦和手機(jī)徘铝,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,448評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來惯吕,“玉大人诊笤,你說我怎么就攤上這事耘纱§潘ⅲ” “怎么了利赋?”我有些...
    開封第一講書人閱讀 162,823評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長堡距。 經(jīng)常有香客問我甲锡,道長兆蕉,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,204評(píng)論 1 292
  • 正文 為了忘掉前任缤沦,我火速辦了婚禮虎韵,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘缸废。我一直安慰自己劝术,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,228評(píng)論 6 388
  • 文/花漫 我一把揭開白布呆奕。 她就那樣靜靜地躺著,像睡著了一般衬吆。 火紅的嫁衣襯著肌膚如雪梁钾。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,190評(píng)論 1 299
  • 那天逊抡,我揣著相機(jī)與錄音姆泻,去河邊找鬼。 笑死冒嫡,一個(gè)胖子當(dāng)著我的面吹牛拇勃,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播孝凌,決...
    沈念sama閱讀 40,078評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼方咆,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了蟀架?” 一聲冷哼從身側(cè)響起瓣赂,我...
    開封第一講書人閱讀 38,923評(píng)論 0 274
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎片拍,沒想到半個(gè)月后煌集,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,334評(píng)論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡捌省,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,550評(píng)論 2 333
  • 正文 我和宋清朗相戀三年苫纤,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片纲缓。...
    茶點(diǎn)故事閱讀 39,727評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡卷拘,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出祝高,到底是詐尸還是另有隱情恭金,我是刑警寧澤,帶...
    沈念sama閱讀 35,428評(píng)論 5 343
  • 正文 年R本政府宣布褂策,位于F島的核電站横腿,受9級(jí)特大地震影響颓屑,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜耿焊,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,022評(píng)論 3 326
  • 文/蒙蒙 一揪惦、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧罗侯,春花似錦器腋、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,672評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至讲弄,卻和暖如春措左,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背避除。 一陣腳步聲響...
    開封第一講書人閱讀 32,826評(píng)論 1 269
  • 我被黑心中介騙來泰國打工怎披, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人瓶摆。 一個(gè)月前我還...
    沈念sama閱讀 47,734評(píng)論 2 368
  • 正文 我出身青樓凉逛,卻偏偏與公主長得像,于是被迫代替她去往敵國和親群井。 傳聞我的和親對(duì)象是個(gè)殘疾皇子状飞,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,619評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容