AWS EC2部署Shiny应用报错:找不到DBI::dbFetch()函数
Hey there, let's work through this error you're facing with your Shiny app connected to RDS MySQL. I've dealt with this exact issue a few times when setting up Shiny apps on EC2, so here's what to check and fix step by step:
1. Verify Your DBI Package Version & Loading
The dbFetch() function was introduced in DBI version 1.0.0 — if you're running an older version of DBI, this function won't exist at all.
First, log into your EC2 instance, launch R, and run this to check your DBI version:
packageVersion("DBI")If the output is less than
1.0.0, you need to update DBI immediately.Also, make sure you're explicitly loading the DBI package in your Shiny script. Even if RMySQL depends on DBI, Shiny's isolated runtime might not load it automatically. Add this line at the top of your app script:
library(DBI) library(RMySQL)
2. Update DBI & RMySQL to Compatible Versions
Outdated or mismatched versions of DBI and RMySQL can cause this function not to be recognized. Run these commands in your EC2 R session to install the latest stable versions:
install.packages(c("DBI", "RMySQL"), dependencies = TRUE)
If you're installing as a non-root user and hit permission issues, use the lib argument to specify a library path accessible to your Shiny server user, like:
install.packages(c("DBI", "RMySQL"), dependencies = TRUE, lib = "/home/ubuntu/R/x86_64-pc-linux-gnu-library/4.2")
(Adjust the path to match your R version and user home directory.)
3. Confirm Shiny's Runtime Environment Matches Your Test Environment
Sometimes the R environment your Shiny server uses is different from the one you test in manually (e.g., multiple R versions installed, or Shiny configured to use a specific library path).
- To check this, add a quick debug line to your Shiny app to print the loaded packages and their versions:
Run the app and check the Shiny server logs (usually atprint(sessionInfo())/var/log/shiny-server/) to see if DBI is loaded and which version is being used. If it's not the updated version, you'll need to adjust your Shiny server configuration to point to the correct R library path.
4. Temporary Workaround (If You Can't Update Packages)
If you're stuck with an older DBI version for some reason, you can use legacy functions that achieve the same result:
- Instead of
dbFetch(result_set), use the olderfetch(result_set)function (note the lowercasef— this is part of the RMySQL package). - Or skip the separate fetch step entirely by using
dbGetQuery(conn, "YOUR_SQL_QUERY"), which runs the query and returns the results directly.
Finally, don't forget to restart your Shiny server after updating packages to ensure the changes take effect. If you're using the official Shiny Server, run:
sudo systemctl restart shiny-server
内容的提问来源于stack exchange,提问作者Christopher Costello

