Input Parameter pop-up box 是严格意义上的 MSAccess.exe GUI 功能。如果通过 ODBC 将 MS Access 作为后端数据库(MS Office 软件之外)运行,使用未知参数的查询将失败,并且在进行 ODBC 调用的脚本上会出现错误。
因此,您需要使用 GWidgets 或 Shiny 等库在 R 中创建类似的 GUI 弹出框,然后将用户的输入值传递给查询。并使用实际的parameterization using RODBCext(RODBC 的扩展)执行此操作,以防恶意用户运行 SQL 注入并可能擦除数据或破坏您的 SQL Server 数据库。
下面是一个使用GWidgets2 和财政年度组合框的示例(下面的屏幕截图)。
库
library(RDOBC)
library(RODBCext)
library(gWidgets2)
library(gWidgets2tcltk)
options(guiToolkit="tcltk")
GUI功能 (预先创建R和SQLServer gif图像)
mainWindow <- function(){
# TOP OF WINDOW
win <- gWidgets2::gwindow("Fiscal Year User Input", height = 200, width = 300)
tbl <- glayout(cont=win, spacing = 8, expand=TRUE)
# IMAGE
tbl[1,1] <- gimage(filename = "RSQLServerGUI.gif",
dirname = "/path/to/gif/image", container = tbl)
# LABEL
tbl[2,1] <- glabel("Fiscal Year Selection: ", container = tbl)
font(tbl[2,1]) <- list(size=12, family="Arial")
# COMBO BOX OF FISCAL YEARS
tbl[3,1, expand=TRUE] <- fiscal_year_cbo <- gcombobox(as.character(c(2012:2018)),
selected = 1, editable = TRUE,
index=TRUE, container = tbl)
font(tbl[3,1]) <- list(size=16, family="Arial")
# COMBO BOX CHANGE FUNCTION (2012 - 2018)
addHandlerChanged(fiscal_year_cbo, handler=function(...) {
fiscal_year_value <- svalue(fiscal_year_cbo) # GET USER SELECTED VALUE
gmessage(paste("You selected FY:", fiscal_year_value))
degrees <- getDegreesData(fiscal_year_value) # GET DATABASE DATA
dispose(win) # CLOSE WINDOW
})
}
查询函数 (在上面的组合框更改处理程序中调用)
getDegreesData <- function(fy_param) {
dbhandle <- odbcDriverConnect('driver={SQL Server};server=SQLSERVER;database=MYDATABASE;trusted_connection=true')
# PREPARED STATEMENT (NO CONCATENATED DATA)
strSQL <- "select Inst, ID, DegreeDate, Degree
from DEGREE
where FY = ?
group by Inst, ID, DegreeDate, Degree
order by Inst, ID, DegreeDate, Degree"
# PASS PARAMETER TO RETURN DATAFRAME
sql_df <- sqlExecute(dbhandle, strSQL, fy_param, fetch=TRUE)
odbcClose(dbHandle)
return(sql_df)
}
运行图形界面
m <- mainWindow()
截图