R Tutorial - Connecting to STEEMSQL - R 教程之 怎么样连接到 STEEMSQL 数据库

R is suitable for data analysis and we can use R to do machine learning after mining the data from STEEMSQL. The first step is to connect to STEEMSQL, and let's do it.

Step 1 - Install the MS SQL package

@arcange 's STEEMSQL is a Microsoft SQL Server, thus we need R to be able to handle the MSSQL connection via the RODBC library. To install the connector in R, run the following command

install.packages("ROBDC")

Step 2 - Reference the RODBC library

After RODBC is installed, you first need to reference it e.g. in R script.

library(RODBC)

Step 3 - Connect via odbcDriverConnect method

Like other programming language, RODBC has a DB-connect method, i.e. odbcDriverConnect which needs to be customised to the following according to STEEMSQL:

conn <- odbcDriverConnect("Driver=SQL Server Native Client 11.0;Server=sql.steemsql.com;Database=DBSteem;Uid=steemit;Pwd=steemit")

Upon success, the connection is stored in conn

Step 4 - Run the query

This is easy to understand, first parameter is the db connection and the second parameter is the actual SQL statement!

sqlQuery(conn, str_c("select voting_power from Accounts where name='justyy'"))

Demo R Function - Get Current Voting Power

Let's wrap this up!

library(RODBC)
library(stringr)

getvp = function(id) {
  conn <- odbcDriverConnect("Driver=SQL Server Native Client 11.0;Server=sql.steemsql.com;Database=DBSteem;Uid=steemit;Pwd=steemit")
  x <- sqlQuery(conn, str_c("select voting_power from Accounts where name='", id, "'"))
  close(conn)
  return(x)
}


R 语言非常适合做数据处理和大数据分析,比如我们可以很容易的通过 STEEMSQL 把数据抓下来再通过R脚本来做一些大数据分析和机器学习。那么首先就是要在R语言里连接数据库,STEEMSQL是基于MS SQL的,所以我们需要:

安装 RODBC

@arcange 's STEEMSQL 是 Microsoft SQL Server, 我们需要在R控制台上运行安装命令

install.packages("ROBDC")

引用 RODBC

在 RODBC包安装好后,需要在R脚本的开头引用RODBC

library(RODBC)

通过 odbcDriverConnect 建立数据库连接

和其它语言类似,在使用数据库前需要建立连接,在RODBC里,我们可以通过 odbcDriverConnect

conn <- odbcDriverConnect("Driver=SQL Server Native Client 11.0;Server=sql.steemsql.com;Database=DBSteem;Uid=steemit;Pwd=steemit")

数据库连接成功后,存于变量 conn

执行SQL

这一步容易理解,第一个参数就是数据库连接,第二个参数是SQL语句。

sqlQuery(conn, str_c("select voting_power from Accounts where name='justyy'"))

R示例,通过STEEMSQL查询 VP

把上面几个合起来!

library(RODBC)
library(stringr)

getvp = function(id) {
  conn <- odbcDriverConnect("Driver=SQL Server Native Client 11.0;Server=sql.steemsql.com;Database=DBSteem;Uid=steemit;Pwd=steemit")
  x <- sqlQuery(conn, str_c("select voting_power from Accounts where name='", id, "'"))
  close(conn)
  return(x)
}


@justyyhttps://justyy.com 的博主,在 @tumutanzi 大哥 的介绍下加入 STEEMIT,写些帖子挣些小钱养家糊口。


@justyy 也是CN 区的点赞机器人,对优质内容点赞,只要代理给 @justyy 每天收利息(年化率14.6%)并能获得一次至少2倍(VP 200%+)的点赞,大鱼 @htliao 都加入了这个计划(530 SP)表示支持。

  1. cn区最低保障系统 上线了!
  2. cn区低保计划(鼓励新人)真的适合你么?

R 教程之 怎么样连接到 STEEMSQL 数据库
R Tutorial – Connecting to STEEMSQL
Steemit 在线工具和API接口
SteemIt Tools and APIs

H2
H3
H4
3 columns
2 columns
1 column
26 Comments