[R-sig-DB] table create from data.frame?

Dirk Eddelbuettel edd @end|ng |rom deb|@n@org
Wed Feb 9 20:31:19 CET 2011


On 9 February 2011 at 11:18, Jeff Hamann wrote:
| Is there some function in any of the db tools for R to generate an SQL table create statement (with optional insert statements) from a data.frame object?

Yes, DBI has had dbWriteTable() for that for a long time.  Here is a complete
example (from the regression tests in RPostgreSQL) writing rock from the
datasets package:

    ## try to load our module and abort if this fails
    stopifnot(require(RPostgreSQL))
    stopifnot(require(datasets))

    ## load the PostgresSQL driver
    drv <- dbDriver("PostgreSQL")

    ## connect to the default db
    con <- dbConnect(drv,
                     user=Sys.getenv("POSTGRES_USER"),
                     password=Sys.getenv("POSTGRES_PASSWD"),
                     host=Sys.getenv("POSTGRES_HOST"),
                     dbname=Sys.getenv("POSTGRES_DATABASE"),
                     port=ifelse((p<-Sys.getenv("POSTGRES_PORT"))!="", p, 5432))


    if (dbExistsTable(con, "rockdata")) {
        print("Removing rockdata\n")
        dbRemoveTable(con, "rockdata")
    }

    dbWriteTable(con, "rockdata", rock)

    ## run a simple query and show the query result
    res <- dbGetQuery(con, "select * from rockdata limit 10")
    print(res)


    ## cleanup
    if (dbExistsTable(con, "rockdata")) {
        print("Removing rockdata\n")
        dbRemoveTable(con, "rockdata")
    }

    ## and disconnect
    dbDisconnect(con)

(The dbConnect is overly verbose / complicated because we want this scripted
without writing down users and passwords, that way we can automate tests in
different places.)

Dirk

-- 
Dirk Eddelbuettel | edd using debian.org | http://dirk.eddelbuettel.com




More information about the R-sig-DB mailing list