从R脚本创建新的MYSQL数据库

blmhpbnm  于 2022-12-20  发布在  Mysql
关注(0)|答案(1)|浏览(78)

我正在尝试从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)

但是,不幸的是,我不能改变给定的数据库.
谢谢你的帮助!

svmlkihl

svmlkihl1#

临时表

两种方法:
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

1.在表格创建中使用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]

重现性:我将docker与mariadb一起使用,您不需要这个,因为您已经在某处启动并运行了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")

相关问题