我使用RMySQL包编写了代码,它可以作为代码工作,但是当我将其编写为函数时,它总是返回
.local(dbObj,...)中的错误: RS_DBI_getConnection中发生内部错误:连接句柄已损坏。
如何解决此问题?
我取出了功能{},它起作用了,但是每次我放回它时,它就会崩溃。当发生问题时,我也尝试固定下来,但是找不到位置。
move_data_summary <- function(path,DSfile,hostname,outpath){
library(RMySQL)
library(readxl)
library(readr)
library(stringi)
library(tidyr)
path <- path
DSfile <- sprintf("%s/%s",path,DSfile)
DS <- read_excel(DSfile,"RunSpec")
pollutantID <- c(31,87,110)
pollutant <- c("NOx","VOC","PM2.5")
ERRORfile <- sprintf("%s/data_summary_error.txt",path)
if (file.exists(ERRORfile)) file.remove(ERRORfile)
write(paste("total lines",length(DS$countyID)),ERRORfile,append = TRUE)
for (c in 1:length(DS$countyID)){
if(DS$countyID[c] %in% NA){
write(paste("error data in line",c),ERRORfile,append = TRUE)
}else{
write(paste("finished data in line",c),ERRORfile,append = TRUE)
database <- DS$`CDM Output Name`[c]
mydb = dbConnect(MySQL(), user='moves', password='moves',
dbname=database, host= hostname)
on.exit(dbDisconnect(mydb))
rs1 = dbSendQuery(mydb, "SELECT countyID, yearID, pollutantID, sourcetypeID, sum(emissionQuant) FROM movesoutput
group by countyID, sourceTypeID, pollutantID")
data_tmp1 = fetch(rs1, n=-1)
all_cons <- dbListConnections(MySQL())
for (con in all_cons)
dbDisconnect(con)
tmpoutfile <- sprintf("%s/%s.csv",outpath,database)
write.csv(data_tmp1,tmpoutfile)
if (c == 1){
data <- data_tmp1[which(data_tmp1$pollutantID == 31 |
data_tmp1$pollutantID == 87 |
data_tmp1$pollutantID == 110),]
}else{
data_tmp <- data_tmp1[which(data_tmp1$pollutantID == 31 |
data_tmp1$pollutantID == 87 |
data_tmp1$pollutantID == 110),]
data <- rbind(data,data_tmp)
}
}
}
write("finished all data",ERRORfile,append = TRUE)
return(data)
}
如果我取出该功能{},它就起作用了。否则,请显示错误
.local(dbObj,...)中的错误: RS_DBI_getConnection中的内部错误:损坏的连接句柄 另外:有50个或更多警告(使用warnings()查看前50个)。
我用过
all_cons <- dbListConnections(MySQL())
for (con in all_cons)
dbDisconnect(con)
断开SQL Server的连接。