我们如何将xml文件直接插入java中的mysql表?
答案 0 :(得分:1)
您可以使用xslt使xml适应特定的mysql格式,之后可以使用LOAD_XML语句。 http://dev.mysql.com/doc/refman/5.5/en/load-xml.html
答案 1 :(得分:0)
“xml文件直接进入mysql
” - >我不清楚它是什么意思。但是,您可以在java中将任何文件作为Binary Steam or byte array
插入数据库。
请查看以下示例...
实施例
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
)