dbDisconnect function of RMySQL library is not closing the DB connection properly. Here is the code I have tried out in my local to test it
library(RMySQL)
execute.query <- function(query){
mydb_con <- dbConnect(MySQL(), user='username', password='pass', dbname='student', host='db_ip')
returned_data <- dbGetQuery(mydb_con, query)
dbDisconnect(mydb_con)
return(returned_data)
}
for(i in c(1:100)){
print(paste0("i = ", i));
execute.query(paste("select now()"));
}
which executes 100 SQL queries sequentially that should ideally create and close new DB connection for each query but after executing the above code, I could see that using this command watch netstat -nat | grep {db_ip} |wc -l
the number of DB connections goes from 0 to 20 until first 20 queries, maintains it at 18-24 connections until 100th query and after 10 seconds the program finished executing, drains to 0 connections.
so my question is why dbDisconnect is not closing the DB connection? is there any nuance that I am missing to understand here?
because of this issue, I am getting Failed to connect to database: Error: Can't create TCP/IP socket (24)
error in my production R code (Huge Multithreaded legacy code base) when the connection reaches 1000+