Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用参数获取R中的SQL数据_Sql_R - Fatal编程技术网

使用参数获取R中的SQL数据

使用参数获取R中的SQL数据,sql,r,Sql,R,我想从MySQL服务器中提取一些数据。因此,我使用以下代码: #connect to database getPlayersHome <- dbGetQuery(con,"SELECT * FROM match_player_home WHERE match_id = 1;") 这很好,但是我想将其包含在一个带有参数的函数中。但如果我这样做: getData <- function(selector){ getPlayersHome <- dbGetQuery(con,

我想从MySQL服务器中提取一些数据。因此,我使用以下代码:

#connect to database
getPlayersHome <- dbGetQuery(con,"SELECT * FROM match_player_home WHERE match_id = 1;")
这很好,但是我想将其包含在一个带有参数的函数中。但如果我这样做:

getData <- function(selector){
   getPlayersHome <- dbGetQuery(con,"SELECT * FROM match_player_home WHERE match_id = selector;")

}

我的查询不起作用,它返回所有内容。您对这里的错误有什么想法吗?

您错误地使用了选择器参数,因为在编写选择器时,它被解释为文本。您可以使用sprintf创建传递参数的sql字符串:

getData <- function(selector){
    sql <- sprintf("SELECT * FROM match_player_home WHERE match_id = %s", selector)
    rs = dbSendQuery(con, sql)
}

sprintf中的字符串%s将被选择器的值替换

您不正确地使用了selector参数,因为您在编写selector时,它被解释为文本。您可以使用sprintf创建传递参数的sql字符串:

getData <- function(selector){
    sql <- sprintf("SELECT * FROM match_player_home WHERE match_id = %s", selector)
    rs = dbSendQuery(con, sql)
}

sprintf中的字符串%s将被选择器的值替换

you函数中的查询不完全相同,我认为您需要类似于paste0SELECT*的东西,来自match_player_home,其中match_id=,selector;您函数中的查询不完全相同,我认为您需要类似paste0SELECT*的内容,来自match_player_home,其中match_id=,selector;代替查询。