View source: R/dbTableFromDataFrame.R
| dbTableFromDataFrame | R Documentation |
The dbTableFromDataFrame() function reads the data from a rectangula region
of a sheet in an Excel file and copies it to a table in a SQLite
database. If table does not exist, it will create it.
dbTableFromDataFrame(
df,
dbcon,
table_name,
id_quote_method = "DB_NAMES",
col_names = NULL,
col_types = NULL,
drop_table = FALSE,
auto_pk = FALSE,
build_pk = FALSE,
pk_fields = NULL
)
df |
the data frame to be saved in the SQLite table. |
dbcon |
database connection, as created by the dbConnect function. |
table_name |
character, the name of the table. |
id_quote_method |
character, used to specify how to build the SQLite
columns' names using the fields' identifiers read from the input file.
For details see the description of the |
col_names |
character vector, names of the columuns to be imported.
Used to override the field names derived from the data frame (using the
quote method selected by |
col_types |
character vector of classes to be assumed for the columns.
If not null, it will override the data types inferred from the input data
frame. Must be of the same length of the number of columns in the input.
If |
drop_table |
logical, if |
auto_pk |
logical, if |
build_pk |
logical, if |
pk_fields |
character vector, the list of the fields' names that
define the |
integer, the number of records in table_name after reading data
from the data frame.
# Create a temporary database and load data frame
# Set up database connection
dbcon <- dbConnect(RSQLite::SQLite(), file.path(tempdir(), "example.sqlite"))
# Create a sample data frame
sample_data <- data.frame(
id = 1:10,
name = paste0("Item_", 1:10),
value = runif(10, 1, 100),
active = c(TRUE, FALSE),
date = Sys.Date() + 0:9,
stringsAsFactors = FALSE,
row.names = NULL
)
# Load data frame with automatic primary key
dbTableFromDataFrame(
df = sample_data,
dbcon = dbcon,
table_name = "SAMPLE_DATA",
drop_table = TRUE,
auto_pk = TRUE
)
# Check the imported data
dbListFields(dbcon, "SAMPLE_DATA")
dbGetQuery(dbcon, "SELECT * FROM SAMPLE_DATA LIMIT 5")
# Load with column selection and custom naming
dbTableFromDataFrame(
df = sample_data,
dbcon = dbcon,
table_name = "SAMPLE_SUBSET",
drop_table = TRUE,
col_names = c("ID", "ITEM_NAME", "ITEM_VALUE", "IS_ACTIVE", "DATE_CREATED")
)
dbGetQuery(dbcon, "SELECT * FROM SAMPLE_SUBSET LIMIT 5")
# Clean up
dbDisconnect(dbcon)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.