我正在try 从R脚本创建新的MySQL数据库,以保存采样函数在其上生成的新表.该函数从用户处获取连接信息,对指定表进行采样,采样后返回表. 下面显示了我的函数的快照,以便更清楚地说明这一 idea . `

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)}

返回的表RandomRowSmping应该保存在新建的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)

但是,不幸的是,我不能更改给定的数据库.

谢谢你的帮助!

推荐答案

Temporary Tables

有两种方法:

  1. 手动创建临时表,需要知道所有字段和字段类型:

    DBI::dbExecute(maria, "create temporary table mytemp (myint int, mychr varchar(16))")
    # [1] 0
    DBI::dbWriteTable(maria, "mytemp", data.frame(myint=1L, mychr="hello world"), append = TRUE)
    DBI::dbGetQuery(maria, "select * from mytemp")
    #   myint       mychr
    # 1     1 hello world
    
  2. 在表创建中使用temporary=TRUE:

    DBI::dbWriteTable(maria, "mytemp2", data.frame(myint2=2L, mychr2="hello world again"), create=TRUE, temporary=TRUE)
    DBI::dbGetQuery(maria, "select * from mytemp2")
    #   myint2            mychr2
    # 1      2 hello world again
    

对于这两个表,这是一个临时表:当当前连接被删除时,它被删除.

DBI::dbDisconnect(maria)
maria <- DBI::dbConnect(RMariaDB::MariaDB(), user="example-user", password="my_cool_secret", host="localhost", db = "mydb")
DBI::dbGetQuery(maria, "select * from mytemp")
# Error: Table 'mydb.mytemp' doesn't exist [1146]
DBI::dbGetQuery(maria, "select * from mytemp2")
# Error: Table 'mydb.mytemp2' doesn't exist [1146]

Reproducibility:我用的是mariadb的DOKER.您不需要这样做,因为您已经在某个地方启动并运行了一个MariaDB实例.

从shell 中:

$ docker run -p 3306:3306 --detach  --name some-mariadb --env MARIADB_USER=example-user --env MARIADB_PASSWORD=my_cool_secret --env MARIADB_ROOT_
PASSWORD=my-secret-pw  mariadb:latest
3babf14f7a8f2010e844a5244475d69ac4dd0856017d190bf531c5187c3e178f

$ docker exec -it  some-mariadb mariadb  -uroot -p
Enter password:
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 6
Server version: 10.9.3-MariaDB-1:10.9.3+maria~ubu2204 mariadb.org binary distribution

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> create database mydb;
Query OK, 1 row affected (0.001 sec)

MariaDB [(none)]> grant all on mydb.* to 'example-user'@'%';
Query OK, 0 rows affected (0.002 sec)

在R中,可以通过以下方式形成连接:

maria <- DBI::dbConnect(RMariaDB::MariaDB(), user="example_user", password="my_cool_secret", host="localhost", db="mydb")

Mysql相关问答推荐

MySQL将JSON值从对象类型更改为数组

插入时发生日期时间字段溢出错误

如何在sql中包含0作为计数?

如何计算具有权重属性的记录数

为两个中的每一个 Select 最大和最小传递条件

生成直到 10 的平方数序列

使用索引进行查询优化

MySQL:根据条件查找某些用户的行位置

有人可以帮我用 R 编程解决这个问题吗?

MySQL 将分组 JSON Select 转换为单个 JSON 对象

提取 MySQL 5.7 连续值的差异

无法通过迁移在现有表中插入行 - Rails 6

如何判断嵌套查询返回的元组中的每个条目是否相同?

在 MySQL 的存储过程中调用存储过程

用序列号mysql更新列

自动登录 phpMyAdmin

MySql 以秒为单位的两个时间戳之间的差异?

获取Count(*)占GROUP BY中所有项目数的百分比

安装 mysql-python (Windows)

PHP mySQL - 将新记录插入表中,主键自动递增