dbSendQuery-methods(RSQLite)
dbSendQuery-methods()所属R语言包:RSQLite
Execute a SQL statement on a database connection
在数据库连接上执行一个SQL语句
译者:生物统计家园网 机器人LoveR
描述----------Description----------
These are the primary methods for interacting with a database via SQL queries.
这是通过SQL查询,与数据库交互的主要方法。
方法----------Methods----------
参考文献----------References----------
<code>DBI.pdf</code> in the base directory of this package or http://stat.bell-labs.com/RS-DBI.
参见----------See Also----------
SQLite, dbDriver, dbConnect, fetch, dbCommit, dbGetInfo, dbReadTable.
SQLite,dbDriver,dbConnect,fetch,dbCommit,dbGetInfo,dbReadTable。
实例----------Examples----------
con <- dbConnect(SQLite(), ":memory:")
data(USArrests)
dbWriteTable(con, "arrests", USArrests)
res <- dbSendQuery(con, "SELECT * from arrests")
data <- fetch(res, n = 2)
data
dbClearResult(res)
dbGetQuery(con, "SELECT * from arrests limit 3")
tryCatch(dbGetQuery(con, "SELECT * FROM tableDoesNotExist"),
error=function(e) { print("caught") })
dbGetException(con)
## The following example demonstrates the use of[#下面的例子演示了如何使用]
## transactions and bound parameters in prepared[在事先准备好的交易和绑定参数]
## statements.[#语句。]
set.seed(0x4554)
make_data <- function(n)
{
alpha <- c(letters, as.character(0:9))
make_key <- function(n)
{
paste(sample(alpha, n, replace = TRUE), collapse = "")
}
keys <- sapply(sample(1:5, replace=TRUE), function(x) make_key(x))
counts <- sample(seq_len(1e4), n, replace = TRUE)
data.frame(key = keys, count = counts, stringsAsFactors = FALSE)
}
key_counts <- make_data(100)
db <- dbConnect(SQLite(), dbname = ":memory:")
sql <- "
create table keys (key text, count integer)
"
dbGetQuery(db, sql)
bulk_insert <- function(sql, key_counts)
{
dbBeginTransaction(db)
dbGetPreparedQuery(db, sql, bind.data = key_counts)
dbCommit(db)
dbGetQuery(db, "select count(*) from keys")[[1]]
}
## for all styles, you can have up to 999 parameters[#所有样式,最多可以有999参数]
## anonymous[匿名]
sql <- "insert into keys values (?, ?)"
bulk_insert(sql, key_counts)
## named w/ :, $, @[#命名为W /,$ @]
## names are matched against column names of bind.data[#名称相匹配的列名bind.data]
sql <- "insert into keys values (:key, :count)"
bulk_insert(sql, key_counts[ , 2:1])
sql <- "insert into keys values ($key, $count)"
bulk_insert(sql, key_counts)
sql <- "insert into keys values (@key, @count)"
bulk_insert(sql, key_counts)
## indexed (NOT CURRENTLY SUPPORTED)[#索引(目前尚不支持)]
## sql <- "insert into keys values (?1, ?2)"[#SQL < - “键插入值(1,2)]
## bulk_insert(sql)[#bulk_insert(SQL)]
sql <- "select * from keys where count = :cc"
dbGetPreparedQuery(db, sql, data.frame(cc = c(95, 403)))
dbDisconnect(db)
转载请注明:出自 生物统计家园网(http://www.biostatistic.net)。
注:
注1:为了方便大家学习,本文档为生物统计家园网机器人LoveR翻译而成,仅供个人R语言学习参考使用,生物统计家园保留版权。
注2:由于是机器人自动翻译,难免有不准确之处,使用时仔细对照中、英文内容进行反复理解,可以帮助R语言的学习。
注3:如遇到不准确之处,请在本贴的后面进行回帖,我们会逐渐进行修订。
|