How can I insert an XML document in PostgreSQL in Java?

后端 未结 4 1149
不思量自难忘°
不思量自难忘° 2021-01-02 18:54

I have a table in Postgresql

DROP TABLE xml_docs;
CREATE TABLE xml_docs(
id serial PRIMARY KEY,
cad_number character(50),
gkuzu_name character(50),
gkuzu xm         


        
相关标签:
4条回答
  • 2021-01-02 19:03

    I'm not sure, but try this:

    First convert your XML to a Java String. Then create an insert statement und use the XMLPARSE method of PostgreSQL to convert your value to the xml type of PostgreSQL:

    INSERT INTO xml_docs(id, gkuzu) VALUES (1, XMLPARSE('<foo><bar>Hello</bar></foo>'));
    

    See: http://wiki.postgresql.org/wiki/XML_Support

    UPDATE:

    Java code example:

    String sql = "INSERT INTO xml_docs(id, gkuzu) VALUES (?, XMLPARSE(?))";
    [...]
    stmt.setString(2, "<foo>Hello World!</foo>");
    

    This should create this statement:

    INSERT INTO xml_docs(id, gkuzu) VALUES (1, XMLPARSE('<foo>Hello World!</foo>'));
    
    0 讨论(0)
  • 2021-01-02 19:14

    Though postgres has native XML Data type, from java end, You can handle with Plain strings.
    You can convert your xml document to String and insert, It should work.

    UPDATE:

    After looking at your error, You need to pass an additional variable to the server through driver URL.

    jdbc:postgresql://localhost/test?stringtype=unspecified
    or
    jdbc:postgresql://localhost/test?user=user&password=pass&stringtype=unspecified
    

    The extra param stringtype=unspecified will remove the type check for the input strings.

    0 讨论(0)
  • 2021-01-02 19:17

    Instead of rewriting the insert statement using PostgreSQL-proprietary syntax, you could use JDBC 4 SQLXML:

    String xml = xml_gkuzu.toString();
    
    SQLXML sqlxml = connection.createSQLXML();
    sqlxml.setString(xml);
    stmt.setSQLXML(3, sqlxml);
    
    0 讨论(0)
  • 2021-01-02 19:17

    An update to the accepted answer if you do not have Postgres built with libxml support:

    Java code example:

    String sql = "INSERT INTO xml_docs(id, gkuzu) VALUES (?, XML(?))";
    [...]
    stmt.setString(2, "<foo>Hello World!</foo>");
    

    This should create this statement:

    INSERT INTO xml_docs(id, gkuzu) VALUES (1, XML('<foo>Hello World!</foo>'));
    

    Thus for version 9.0 and greater you may want to switch XMLPARSE ==> XML. Otherwise you will need special support for XMLPARSE

    From Postgres Documentation:

    The function-like expressions xmlparse and xmlserialize for converting to and from type xml are not repeated here. Use of most of these functions requires the installation to have been built with configure --with-libxml.

    0 讨论(0)
提交回复
热议问题