How it works...

The dbConnect() function is used either to connect with an existing database or to create a new one if there aren't any. In this example, testdbSQL is a new database that has been created using the dbConnect() function. This function takes the database driver string as one of the inputs and then the name of the database. Once the database connection string has been created, you are ready to interact with the database.

After creating the database, the next thing is to create a data table and insert data into it. The following code line is to create a data table and insert actual data from the source data mtcars from the datasets library:

    carTable <- dbWriteTable(con =  dbNew, name = "cardata", value =   
mtcars)

You can check whether the table has been created or not by executing the following code line:

    dbListTables(dbNew)
    [1] "cardata"

Once you see that the new data table has been created, you can query from the table. The following line is to extract the rows with the column "am" ==0:

    autocars <- dbGetQuery(conn = dbNew, 'SELECT * FROM "cardata" WHERE  
"am"==0')

The output of the newly created subset of original the data is as follows:

    > head(autocars)
              row_names  mpg cyl  disp  hp drat    wt  qsec vs am gear carb
    1    Hornet 4 Drive 21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
    2 Hornet Sportabout 18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
    3           Valiant 18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
    4        Duster 360 14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4
    5         Merc 240D 24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2
    6          Merc 230 22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset