我正在尝试从R脚本创建新的MYSQL数据库,以保存采样函数在其上生成的新表。该函数从用户处获取连接信息,对指定的表进行采样,然后在采样后返回该表。下面显示了我的函数的快照,以更清楚地说明该想法。
SQLRowRandomSampling <- function(username,passwords,databaseName,TableName,
SamplingSize){
#' establish the connection with the selected database
ConnectedDb <- dbConnect(RMariaDB::MariaDB(), user=username,
password=passwords, dbname=databaseName,
host='localhost')
#' checking if the entered table exist in the selected database
x <- tryCatch({
dbframe <- dbReadTable(ConnectedDb,TableName)},
error = function(e){
#' if not stop the function
stop('Table does not exist! Try again please.')
}
)
#' get number of rows in the selected table
actualRowNumber <- nrow(dbframe)
# check if the entered sampling size is valid
if(SamplingSize<1){
stop("Entered sampling size must be a valid number")}
else if (SamplingSize >= actualRowNumber){
stop("You should eneter a sampling size that is less than the rows number
of the selected table")}
# start row random sampling
RandomRowSmpling<- sample_n(dbframe, SamplingSize)
# return the result
return(RandomRowSmpling)}
返回的表“RandomRowSmpling”应保存在新创建的MYSQL数据库中,以供以后使用。
我知道如何创建新的SQLite数据库如下:
#' create new database named Sampling_Database
ConnectedCreatedDb <- dbConnect(drv = RSQLite::SQLite(),
dbname= 'Sampling_Database')
然而,对于我的项目建议它应该是MYSQL而不是SQLite。任何想法如何创建新的MYSQL数据库,以保存它的结果表?
此外,我知道我可以使用以下命令将创建的表添加到我原来的MYSQL数据库:
dbWriteTable(conn = ConnectedDb, name = "RandomRowSmpling"
, value = RandomRowSmpling)
但是,不幸的是,我不能改变给定的数据库.
谢谢你的帮助!
1条答案
按热度按时间svmlkihl1#
临时表
两种方法:
1.手动创建临时表需要了解所有字段和字段类型:
1.在表格创建中使用
temporary=TRUE
:对于这两种情况,这是一个临时表:当当前连接被丢弃时,它也被丢弃。
重现性:我将docker与
mariadb
一起使用,您不需要这个,因为您已经在某处启动并运行了MariaDB示例。从 shell :
在R中,连接可以用以下方式形成: