1. Import table data
After successfully connecting to a database,
2. con
like this, you'll probably want to see what's in there.
3. List and import tables
The first step is listing all the table in the database. You can do this with the dbListTables function. Simply pass the con variable.
As expected, we get a character vector of length three, corresponding to the table names I've introduced earlier. Next, you can choose to actually read the data from one of these tables, for example from the employees table. You use the dbReadTable function for this. Again, you specify the connection to use, con, but this time you also specify which table data you want to import:
The result is a data frame, with exactly the same contents as in the original database table.
DBI also specifies functions to create new tables, store new data in tables and to remove tables, but this is not really related to importing data so I won't talk about that here. The functions we've covered up to now already provide a pretty good starting point. Oh no, wait, there's one last thing!
It's always polite to explicitly disconnect your database after you're done. You do this with dbDisconnect, as follows.
If you now try to print con, you'll see that it is no longer available. Good riddance,
4. Let's practice!
off to the exercises now!