我正面临 R Shiny 和 sqlite 的问题。我的应用程序应该对用户进行身份验证并加载他/她的首选项。
这是我的代码:
服务器.R
library(shiny)
library(shinyBS)
library(dplyr)
library(lubridate)
library(DBI)
library(RSQLite)
############################
# Database functions #
###########################
# Connect the user to the dtabase app
connect <- function(userName,pwd){
#Put a generic path here
db <- dbConnect(SQLite(), dbname = "my_path/database.db")
#Query to get the correct passwd
qry = paste('SELECT password from USERS where name = "',userName,'"')
res= dbGetQuery(db,qry )
ifelse(res==pwd,"connected","unable to connect to the database")
dbDisconnect(db)
}
function(input, output,session) {
observeEvent(input$connectButton, {
userName= renderPrint(input$username)
print(userName)
userPwd = paste(input$password)
connect(user = userName,pwd = userPwd)
})
ui.R
shinyUI(fluidPage(
titlePanel("Authentification"),
textInput('username', label="User name"),
textInput('password', label= "password"),
actionButton("connectButton", label='Connect'),
actionButton("subscribeButton",label='Subscribe')
)
)
app.R
library(shiny)
library(shinyBS)
####### UI
ui <- source("ui.R")
####### Server
varserver <- source("server.R")
####### APP
shinyApp(ui = ui, server = varserver)
我的问题是当我想为查询放置 TextInput 的内容时。我尝试了几种方法
在当前版本中,renderPrint(input$username) 返回给我的东西似乎是一个函数,但它似乎没有用。
我也尝试了另一种方式,只使用
userName=paste(input$userName)
这将返回 textField 的内容,但是当我将它集成到它放置的查询中时
[1] "SELECT password from USERS where name = \" test \""
然后我得到了错误
Warning: Error in matrix: length of 'dimnames' [2] not equal to array extent
我的目标是有这样的查询
"Select password FROM USERS where name = "username"
与
username
表示 TextInput 的内容。编辑
我知道使用这个版本的查询,它提出了一个语法正确的查询
qry = paste0('SELECT password from USERS where name = \'',userName,'\'')
res= dbGetQuery(db,qry )
但我现在面临这个问题:
Warning: Error in matrix: length of 'dimnames' [2] not equal to array extent
当我运行该方法时
connect(db,qry)
我认为问题出在我获取 TextInput 内容的方式上:我使用
function(input, output,session) {
observeEvent(input$connectButton, {
userName= paste0(input$username)
userPwd = paste0(input$password)
connect(user = userName,pwd = userPwd)
})
你怎么看待这件事 ?
最佳答案
我找到了一个可行的解决方案
connect <- function(userName,pwd){
#Put a generic path here
db <- dbConnect(SQLite(), dbname = "my_path/database.db")
#Query to get the correct passwd
qry = paste0("SELECT password from USERS where name = \'",userName,"\'")
res= dbGetQuery(db,qry )
res = paste0(res)
ifelse(res==pwd,print("connected"),print("unable to connect to the database"))
dbDisconnect(db)
}
我只是在简单的引号之间添加参数
关于R Shiny 将 TextInput 的内容放入 sql 查询中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35589604/