RJDBC: R连接Oracle无法删除或删除表

3
我正在使用RJDBC连接到本地数据库。这使我可以轻松使用dbGetQuery进行选择查询,并使用dbWriteTable创建表格。
然而,我无法在我的R控制台上直接执行DROP TABLE或DELETE或SELECT INTO等操作。当我直接在SQL Developer中执行这些操作时,它们是有效的,但是从R传递查询时却无效。
我该如何使用R执行不是SELECT语句的数据库记录操作?
2个回答

2
我建议您使用其他类型代替。 dbGetQuery 是基于查找和迭代数据库而不是操作记录的。 类似的问题之前已经被问过,可以在这里找到; 我没有找到一个好的R例子,但如果有帮助的话,可以在这里找到一个好的Java例子。

编辑:

我找到了我所说的类型!虽然花了一些时间 - sqlQuery 允许您运行几乎任何查询,也就是说,更改数据库记录。下面是我从这个来源修改的示例:

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搞混了,但不用担心,因为我也找到了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中是否有类似的函数吗? - Anton
@tony 我相当确定这次我做对了,看看我的编辑 :) - A. Abramov

1
这类似于另一个已回答的问题这里
基本上,dbGetQuery()正如其名称所示,用于发送查询并接收它们的结果。
如果您想向数据库发送通用语句,例如“删除表”等,则可以使用:
dbSendUpdate(connection_object, "drop table table_name")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接