myPostgresConnect.R 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. #' PostgreSQL - Create a connection object
  2. #' @details Ühenduse loomine PostgreSql andmebaasiga.
  3. #' @param host Name or the numeric IPaddress of the host to connect to.
  4. #' @param dbname The database name.
  5. #' @param user PostgreSQL user name to connect as. Defaults to be the same as the operating system name of the user running the application.
  6. #' @param password Password to be used if the server demands password authentication.
  7. #' @param port Port number to connect to at the server host.
  8. #' @param type Connection type "RPostgres" or "RPostgreSQL". RPostgres is default.
  9. #' @return return message.
  10. #' @seealso \code{\link{myPostgresConnect}}, \code{\link{myPostgresDropTable}},
  11. #' \code{\link{myPostgresCreateGisDb}}, \code{\link{myPostgresImprotShp}}
  12. #' @examples \dontrun{
  13. #' con <- myPostgresConnect(host = '192.168.255.26', port = 5432,
  14. #' user = 'osm', password = 'osm', dbname = 'shp')
  15. #'
  16. #' }
  17. #'
  18. #' @export
  19. #'
  20. myPostgresConnect <- function(host = '192.168.255.26', port = 5432,
  21. user = 'osm', password = 'osm', dbname = 'shp',
  22. type = c("RPostgres", "RPostgreSQL")) {
  23. con = NULL
  24. if(length(type)>1) type <- type[1]
  25. driver <- RPostgres::Postgres()
  26. if(tolower(type)=="rpostgresql") driver <- RPostgreSQL::PostgreSQL()
  27. try(con <- DBI::dbConnect(driver, host = host, port = port, user = user, password = password, dbname = dbname),
  28. silent = FALSE)
  29. # Check is connection valid
  30. # DBI::dbIsValid(con) - see ei toimi RPostgreSQL ühenduse korral.
  31. if(is.null(con)){
  32. message(paste0("DB connection is not valid!"))
  33. return()
  34. }
  35. con
  36. }