使用Java插入ExistDB

时间:2018-11-15 15:58:34

标签: java xquery exist-db

我在使用Java将新节点插入到exist-db时遇到问题。

如果我从eXide运行此Xquery,它将运行正常并插入新部门:

更新插入 1 A A 到/ departamentos

但是,如果我尝试从Java进行操作,它会指出存在语法错误。代码是:

    String queryString = "update insert <DEP_ROW><DEPT_NO>1</DEPT_NO><DNOMBRE>A</DNOMBRE><LOC>A</LOC></DEP_ROW> into /departamentos";

    consulta = conn.prepareExpression(queryString);
    consulta.executeQuery();

错误是:

Exception in thread "main" javax.xml.xquery.XQException:
XQJQS001 - Invalid XQuery syntax, syntax does not pass static 
validation.
Root Cause:
XQueryParseException: Encountered "insert" at line 1, column 8.
Was expecting one of:
<EOF> 
"%%%" ...
"=" ...
"," ...
"or" ...
"and" ...
"to" ...
"*" ...
"div" ...
"idiv" ...
"mod" ...
"union" ...
"|" ...
"intersect" ...
"except" ...
"instance" ...
"treat" ...
"castable" ...
"cast" ...
"!=" ...
"<=" ...
">" ...
">=" ...
"eq" ...
"ne" ...
"lt" ...
"le" ...
"gt" ...
"ge" ...
"is" ...
"<<" ...
">>" ...
"[" ...
"-" ...
"+" ...
"<" ...
"/" ...
"//" ...
"(" ...

at Visualizar.insertadep(Visualizar.java:58)
at Visualizar.main(Visualizar.java:23)
at Visualizar.insertadep(Visualizar.java:58)
at Visualizar.main(Visualizar.java:23)

非常感谢您的帮助。

谢谢

1 个答案:

答案 0 :(得分:1)

我遇到了与Yeray完全相同的问题,并且遇到了这篇文章。现在,我已经找到了解决方案,因此我将分享我的代码,希望对Yeray或其他人有所帮助。

public class InsertDepartment {

public static final String DRIVER = "org.exist.xmldb.DatabaseImpl";
public final static String URI = "xmldb:exist://localhost:8080/exist/xmlrpc";
public final static String COLLECTION = "/db/first_steps";
public final static String USERNAME = "admin";
public final static String PASSWORD = "";

public static void main(String[] args) throws Exception {
    String value = "";

    Class cl = Class.forName(DRIVER);
    Database database = (Database) cl.newInstance();
    DatabaseManager.registerDatabase(database);
    Collection col = DatabaseManager.getCollection(URI + COLLECTION, USERNAME, PASSWORD);

    int depNumber = 42;
    String depName = "Department 42";
    String depAddress = "42 Galaxy Avenue, Betelgueuse 23458 OH";

    String sQuery = "update insert <department><dep_number>" + depNumber
            + "</dep_number><dep_name>" + depName + "</dep_name><dep_address>"
            + depAddress + "</dep_address></department> into /departments";

    EXistXQueryService service = (EXistXQueryService) col.getService("XQueryService", "1.0");
    service.setProperty("indent", "yes");
    service.query(sQuery);
}

请注意,为了使此代码正常工作,我最终获得了项目中的以下库列表。某些不需要此代码才能起作用。

exist-xqj-1.0.1.jar
j8fu-1.21.jar
log4j-1.2-api-2.11.0.jar
log4j-api-2.11.0.jar
log4j-core-2.11.0.jar
log4j-jul-2.11.0.jar
log4j-slf4j-impl-2.11.0.jar
org.apache.commons.pool.jar
org-apache-commons-logging.jar
ws-commons-util-1.0.2.jar
xmldb-api-1.7.0.jar
xmlrpc-client-3.1.3.jar
xmlrpc-common-3.1.3.jar
xqj2-0.0.1.jar
xqjapi.jar
exist.jar
exist-optional.jar

此外,我还必须将文件log4j2.xml添加到项目的 src 文件夹中。您可以在this post中找到此文件的示例。