Advertisement
Guest User

Untitled

a guest
Feb 7th, 2016
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 1.79 KB | None | 0 0
  1. #Keep in mind, this code will not work if you do not have the same database as mine.
  2. library(RMySQL)
  3.  
  4. #This will connect to the database. user is your user name, password is password, dbname is the name of the
  5. #database that you are trying to connect to, for host just leave it as 'localhost', the on.exit is for
  6. #what to do when you want to disconnect.
  7. mydb = dbConnect(MySQL(), user='bjolivarez', password='insertpassword', dbname='recipes', host='localhost')
  8. on.exit(dbDisconnect(mydb))
  9.  
  10. #This is just a variable that provides an example of data to insert into the database.
  11. kat = "ketchup"
  12.  
  13. #This function will show all tables in the database
  14. dbListTables(mydb)
  15.  
  16. #This is a variable that holds an SQL command to insert the kat variable into the database. The id is NULL,
  17. #because, the database is configured ina way to give ids to new data inserted
  18. sql = sprintf("INSERT INTO `recipes`.`ingredients` (`id`, `name`) VALUES (NULL, '%s');", kat)
  19.  
  20. #This is another variable that holds a command to grab all info in the table labeled "ingredients"
  21. #uncomment to use this command instead.
  22. #rs = dbSendQuery(mydb, "SELECT * FROM ingredients order by id ASC;")
  23.  
  24. #Here is the next example of a variable that represents sending a command to the database. mydb is the
  25. #database connection from earlier sql is the insert sql command from earlier
  26. rs = dbSendQuery(mydb, sql)
  27.  
  28. #This variable stores the data from rs, the command used on the specified database. n=20 is simply how many rows
  29. #from the table you wish to grab
  30. data = fetch(rs, n = 20)
  31.  
  32. #This clears the query that was stored in rs so you can use rs for another command
  33. dbClearResult(rs)
  34.  
  35. #This simply gets the id of the last piece of data you inserted into the table
  36. id <- dbGetQuery(mydb, "select last_insert_id();")[1,1]
  37.  
  38. #Shows the id
  39. id
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement