mysql - 查询变量 RMySQL

标签 mysql r

我试过这个脚本来使用 RMySQL 在表中选择一个字段:

mydb <- dbConnect(MySQL(), dbname="***", user='***',host='***')
a<-29553
b<-31097
c<-'chr1'
s<-'+'
res<-dbSendQuery(mydb, "SELECT name FROM wgEncodeGencodeBasicV27 WHERE 
chrom=c AND strand=s AND txStart=a AND txEnd=b")

但它返回错误:“‘where 子句’中的未知列‘c’”。 为什么?如何更正脚本?

最佳答案

基本上这个想法是您可以在变量的帮助下动态地准备您的查询。这消除了将变量作为参数单独发送的需要。 sprintf 非常适合这个目的。

OP 为例。方法应该是:

#Variables to be used in query
a<-29553
b<-31097
c<-'chr1'
s<-'+'

library(RMySQL)

mydb <- dbConnect(MySQL(), dbname="***", user='***',host='***')

#Prepare a query format string with place holders for variables. 
queryFormat <- "SELECT name FROM wgEncodeGencodeBasicV27 
WHERE chrom=`%s` AND strand=`%s` AND txStart=%d AND txEnd=%d"

#Use sprintf to prepare the query
query <- sprintf(queryFormat, c, s, a, b)

res<-dbSendQuery(mydb, query)

#The final query which has been send to Database:
#[1] "SELECT name FROM wgEncodeGencodeBasicV27 
# WHERE chrom=`chr1` AND strand=`+` AND txStart=29553 AND txEnd=31097"

关于mysql - 查询变量 RMySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49560506/

相关文章:

mysql regexp_replace 更新

r - (预)向函数工厂和内部提供变量

r - 使用其他列作为参数在 summary_at() 中起作用

php - Laravel 查询生成器左连接中的两个表

php - mysql文本字段中的HTML标签

php - 在查询中放置 IF (MYSQL)

r - 使用 "rticles"包时如何更改 RMarkdown 中的字体?

r - ggplot geom_point 的圆似乎不是圆形的

r - 多次迭代后出现 %dopar% 错误

mysql - 表示不应该添加 Id