1

我们如何在java中将xml文件直接插入到mysql表中?

4

2 回答 2

1

您可以使用 xslt 将您的 xml 调整为特定的 mysql 格式,然后您可以使用 LOAD_XML 语句。 http://dev.mysql.com/doc/refman/5.5/en/load-xml.html

于 2013-10-30T07:27:21.357 回答
0

“将xml文件直接放入一个mysql”-->我不清楚这是什么意思。但是,您可以像Binary Steam or byte array在java中一样将任何文件插入数据库。请检查以下示例...

例子

public class InsertXML {
    private static final String INSERT_SQL =  "INSERT INTO ATTACHMENT(FILENAME, MIMETYPE, CONTENT) values(?, ?, ?)";

    public void insert(File xmlFile) {
         PreparedStatement ps = null;
         Connection con = null;
         try {
             ps = con.prepareStatement(INSERT_SQL);
             ps.setString(1, xmlFile.getName());
             ps.setString(2, getMimeType(xmlFile));
             ps.setBinaryStream(3, new FileInputStream(xmlFile));
             ps.executeUpdate();
         } catch (SQLException e) {
             // CLOSE ps and con;
         } catch (FileNotFoundException e) {
            // CLOSE ps and con;
         } finally {
             // CLOSE ps and con;
         }
     }

     public String getMimeType(File xmlFile) {
         String mimeType = null;
        try {
            InputStream is = new BufferedInputStream(new FileInputStream(xmlFile));
            mimeType = URLConnection.guessContentTypeFromStream(is);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return mimeType;
     }

     public static void main(String[] args) {
         InsertXML insertXML = new InsertXML();
         insertXML.insert(new File("D:\test.xml"));
     }
}

SQL

CREATE TABLE ATTACHMENT (
  FILENAME VARCHAR(45) NOT NULL,
  MIMETYPE VARCHAR(45) NOT NULL,
  CONTENT LONGBLOB NOT NULL
) 
于 2013-10-30T07:54:00.927 回答