Advertisement
Guest User

Untitled

a guest
Feb 8th, 2016
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.04 KB | None | 0 0
  1. # install the package
  2. install.packages("RMySQL")
  3.  
  4.  
  5. # load the package
  6. library(RMySQL)
  7.  
  8.  
  9. # create a MySQL connection object
  10. con <- dbConnect(MySQL(),
  11. user = 'root',
  12. password = 'password',
  13. host = 'localhost',
  14. dbname = 'database_name')
  15.  
  16.  
  17. # connection summary
  18. summary(con)
  19.  
  20.  
  21. # database information
  22. dbGetInfo(con)
  23.  
  24.  
  25. # list of tables in the database
  26. dbListTables(con)
  27.  
  28.  
  29. # list of fields in table city
  30. dbListFields(con, "city")
  31.  
  32.  
  33. # MYSQL data type
  34. dbDataType(RMySQL::MySQL(), "a")
  35. dbDataType(RMySQL::MySQL(), 1:5)
  36. dbDataType(RMySQL::MySQL(), 1.5)
  37.  
  38.  
  39. # create table in the database
  40. x <- 1:10
  41. y <- letters[1:10]
  42. trial <- data.frame(x, y, stringsAsFactors = FALSE)
  43. dbWriteTable(con, "trial", trial)
  44.  
  45.  
  46. # read entire table from the database
  47. dbReadTable(con, "trial")
  48.  
  49.  
  50. # extract rows from a table
  51. dbGetQuery(con, "SELECT * FROM trial LIMIT 5;")
  52.  
  53.  
  54. # extract data in batches
  55. query <- dbSendQuery(con, "SELECT * FROM trial;")
  56. data <- dbFetch(query, n = 5)
  57.  
  58.  
  59. # query information
  60. res <- dbSendQuery(con, "SELECT * FROM trial;")
  61. dbGetInfo(res)
  62.  
  63.  
  64. # latest query executed
  65. res <- dbSendQuery(con, "SELECT * FROM trial;")
  66. dbGetStatement(res)
  67.  
  68.  
  69. # number of rows fetched from the database
  70. res <- dbSendQuery(con, "SELECT * FROM trial;")
  71. data <- dbFetch(res, n = 5)
  72. dbGetRowCount(res)
  73.  
  74.  
  75. # number of rows affected by the query
  76. dbGetRowsAffected(res)
  77.  
  78.  
  79. # info about columns of the table on which query has been executed
  80. res <- dbSendQuery(con, "SELECT * FROM trial;")
  81. dbColumnInfo(res)
  82.  
  83.  
  84. # free resources
  85. res <- dbSendQuery(con, "SELECT * FROM trial;")
  86. dbClearResult(res)
  87.  
  88.  
  89. # overwrite table in the database
  90. x <- sample(100, 10)
  91. y <- letters[11:20]
  92. trial2 <- data.frame(x, y, stringsAsFactors = FALSE)
  93. dbWriteTable(con, "trial", trial2, overwrite = TRUE)
  94.  
  95.  
  96. # append data to the table in the database
  97. x <- sample(100, 10)
  98. y <- letters[5:14]
  99. trial3 <- data.frame(x, y, stringsAsFactors = FALSE)
  100. dbWriteTable(con, "trial", trial3, append = TRUE)
  101.  
  102.  
  103. # remove table trial
  104. dbRemoveTable(con, "trial")
  105.  
  106.  
  107. # disconnect from the database
  108. dbDisconnect(con)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement