Guest User

Untitled

a guest
Feb 18th, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.41 KB | None | 0 0
  1. # load R mysql library
  2. # this library needs to be installed via below command
  3. # install.packages("RMySQL")
  4. library(RMySQL)
  5.  
  6.  
  7. # Create mysql database connection and return it, Im running mysql with docker
  8. # here, please refere README.md for more information
  9. # db username = root
  10. # db password = root
  11. # db name = senz
  12. # db host = localhost/127.0.0.1
  13. getConn = function() {
  14. conn = dbConnect(
  15. MySQL(),
  16. user='root',
  17. password='root',
  18. dbname='senz',
  19. host='127.0.0.1'
  20. )
  21.  
  22. return(conn)
  23. }
  24.  
  25.  
  26. # Read data from owls table and print them, I have used two ways to querying the
  27. # data
  28. get = function() {
  29. # get database connection first
  30. conn = getConn()
  31.  
  32. # select statement via frames
  33. rs = dbReadTable(conn, 'owls')
  34. print(rs)
  35.  
  36. # select statement via raw sql query
  37. sql = "select * from owls"
  38. rs = dbSendQuery(conn, sql)
  39. data = fetch(rs)
  40. print(data)
  41. dbClearResult(rs)
  42. }
  43.  
  44.  
  45. # Inset data into owls table, simpley create insert query and exeucute it
  46. # name = given name of owl
  47. # phone = given phone no of owl
  48. put = function(name, phone) {
  49. # get database connection first
  50. conn = getConn()
  51.  
  52. # insert statement
  53. sql <- sprintf("insert into owls(name, phone) values('%s', '%s')", name, phone)
  54. rs = dbSendQuery(conn, sql)
  55. dbClearResult(rs)
  56. }
  57.  
  58. # insert some data
  59. put("python", "067723232")
  60. put("java", "07782323")
  61.  
  62. # read data
  63. get()
Add Comment
Please, Sign In to add comment