我们如何直接在Java中的mysql表中插入xml文件?
You can adapt your xml to specific mysql format using xslt and after it you can use LOAD_XML statement. http://dev.mysql.com/doc/refman/5.5/en/load-xml.html
"xml file directly into a mysql
" --> I am not clear what does it mean.But, you can insert any files to database as Binary Steam or byte array
in java. Please check below example...
EXAMPLE
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
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.