【问题标题】:RJDBC: R to Oracle cannot DELETE or DROP TABLERJDBC:R 到 Oracle 不能 DELETE 或 DROP TABLE
【发布时间】:2015-08-03 20:58:38
【问题描述】:

我正在使用 RJDBC 连接到本地数据库。这使我可以使用dbGetQuery 轻松进行SELECT 查询,并使用dbWriteTable 创建表。

但是,我无法直接从我的 R 控制台找出 DROP TABLE 或 DELETE 或 SELECT INTO 的方法。当我直接在 SQL Developer 中执行这些操作时,这些事情会起作用,但当我将查询从 R 传递到数据库时则不会。

如何使用 R 执行不是 SELECT 语句的数据库记录操作?

【问题讨论】:

    标签: r oracle rjdbc


    【解决方案1】:

    我会尝试使用不同的类型。 dbGetQuery 以查找和迭代数据库为基础,而不是操纵它的记录。 类似问题被问到before; 我找不到一个不错的 R 示例,但如果有帮助,可以找到一个不错的 java 示例 here:

    编辑:

    我找到了我所说的类型!花了我一段时间,无论如何 - sqlQuery 允许您运行几乎任何查询,即 - 数据库记录的更改。示例我修改自this 来源:

    res <- sqlQuery(con1,"DELETE TABLE TESTDATA", errors=FALSE) 
    # res will now hold the result of the query.
    # -1 means error, otherwise iteration is sucessful, and it will hold the number of rows affected.
    if (res == -1){ #if something messed up
     cat ("An error has occurred.\n")
     msg <- odbcGetErrMsg(con1) #Use your connection for this.
     print (msg)
    } else {
      cat ("Table was deleted successfully.\n")
    }
    

    编辑 2

    我把它与 RODBC 混淆了,但是没有理由担心,因为我也找到了 RJDBC 替代方案!它被称为dbSendUpdate。示例:

    # Assuming you have the connection saved as conn; these example shows how to use dbSendUpdate to create tables and insert values.
    # You could use it with every non-selective query, that is, which manipulates the record (update,delete,insert,drop etc.)
    # create table, with dbSendUpdate:
    dbSendUpdate(conn, "CREATE TABLE foo(a INT,b VARCHAR(100))")
    # insert value, bind parameters to placeholders in statement:
    dbSendUpdate(conn, "INSERT INTO foo VALUES(?,?)", 42, "bar")
    # feel free to modify the query itself, these are just example values.
    

    【讨论】:

    • sqlQuery 是 RODBC 包中的一个函数,不幸的是,它不再适用于当前版本的 R。我使用的是 3.1 版,它不允许我安装 RODBC。你知道RJDBC中有类似的功能吗?
    • @tony 很确定这次我明白了,看看我的编辑 :)
    【解决方案2】:

    这类似于另一个已回答的问题here

    顾名思义,基本上 dbGetQuery() 用于发送查询并接收其结果。

    如果您想向数据库发送一般语句,例如“drop table”等。 你可以使用:

    dbSendUpdate(connection_object, "drop table table_name")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-24
      • 2020-05-11
      • 1970-01-01
      • 2012-05-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多