Search code examples
rodbcprintfsnowflake-cloud-data-platform

How to reference external variables inside a sprintf() function in R


I am trying to write a function to connect to a snowflake database at work. The current function takes the following form -


library(DBI)
    library(dplyr)
    library(dbplyr)
    library(odbc)

username <- "myusername@work.com"
    
    hs_snowflake_connection <- dbConnect(
        odbc::odbc(), 
        .connection_string = sprintf(
            "
      Driver={SnowflakeDSIIDriver};
      uid=myusername@work.com; 
      authenticator=externalbrowser; 
      server=work.us-east-1.snowflakecomputing.com; 
      role=ROLE; 
      warehouse=WAREHOUSE; 
      database=DATABASE; 
      schema=TEAM;
    ", 
    username
        ),
    timeout = 10
    )

I am trying to edit this code but instead reference uid, server, warehouse, and team from variables saved as R environment variables, but I'm not sure how to reference such variables inside the sprintf function. Any help will be appreciated.


Solution

  • use %s

    sprintf(
                "
          Driver={SnowflakeDSIIDriver};
          uid=%s; 
          authenticator=externalbrowser; 
          server=work.us-east-1.snowflakecomputing.com; 
          role=ROLE; 
          warehouse=WAREHOUSE; 
          database=DATABASE; 
          schema=TEAM;
        ", 
        username
            )