Guest User

Untitled

a guest
Mar 22nd, 2018
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.30 KB | None | 0 0
  1. library(RPostgreSQL)
  2.  
  3. # Enter the values for you database connection
  4. dsn_database = "northwind"
  5. dsn_hostname = "localhost"
  6. dsn_port = "5432"
  7. dsn_uid = "kilia"
  8. dsn_pwd = ""
  9.  
  10. # Create the database connection
  11. tryCatch({
  12. drv <- dbDriver("PostgreSQL")
  13. print("Connecting to database")
  14. conn <- dbConnect(drv,
  15. dbname = dsn_database,
  16. host = dsn_hostname,
  17. port = dsn_port,
  18. user = dsn_uid,
  19. password = dsn_pwd)
  20. print("Connected!")
  21. },
  22. error=function(cond) {
  23. print("Unable to connect to database.")
  24. })
  25.  
  26. # List tables existing in the database 'northwind'
  27. cursor <- dbGetQuery(conn, "SELECT table_name
  28. FROM information_schema.tables
  29. WHERE table_schema='public'
  30. AND table_type='BASE TABLE'")
  31. print(cursor)
  32.  
  33. # Query data
  34. df <- dbGetQuery(conn, "SELECT * FROM categories LIMIT 10")
  35. print(df)
  36.  
  37. # Create a table
  38. dbSendQuery(conn, "DROP TABLE IF EXISTS Cars")
  39. dbSendQuery(conn, "CREATE TABLE Cars(Id INTEGER PRIMARY KEY, Name VARCHAR(20), Price INT)")
  40.  
  41. # Insert data into a table
  42. dbSendQuery(conn, "INSERT INTO Cars VALUES(1,'Audi',52642)")
  43. dbSendQuery(conn, "INSERT INTO Cars VALUES(2,'Mercedes',57127)")
  44.  
  45. # Close the database connection
  46. dbDisconnect(conn)
Add Comment
Please, Sign In to add comment