springboot项目 java写一个工具类,查找出mysql数据库中其中一个库的所有表和字段和字段类型并生成一个xml文件
时间: 2023-05-23 19:02:07 浏览: 138
数据库设计库表结构导出工具+springboot构建+mysql库表导出
可以通过以下代码实现:
```java
public void generateXml(String dbName) {
String url = "jdbc:mysql://localhost:3306/" + dbName + "?useSSL=false";
String username = "root";
String password = "password";
try (Connection conn = DriverManager.getConnection(url, username, password);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SHOW TABLES")) {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("database");
doc.appendChild(rootElement);
while (rs.next()) {
String tableName = rs.getString(1);
Element tableElement = doc.createElement("table");
tableElement.setAttribute("name", tableName);
rootElement.appendChild(tableElement);
DatabaseMetaData meta = conn.getMetaData();
ResultSet columns = meta.getColumns(null, null, tableName, null);
while (columns.next()) {
String columnName = columns.getString("COLUMN_NAME");
String columnType = columns.getString("TYPE_NAME");
Element columnElement = doc.createElement("column");
columnElement.setAttribute("name", columnName);
columnElement.setAttribute("type", columnType);
tableElement.appendChild(columnElement);
}
}
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("database.xml"));
transformer.transform(source, result);
System.out.println("XML file generated successfully.");
} catch (Exception e) {
e.printStackTrace();
}
}
```
其中,`dbName`为要查询的数据库的名称。生成的XML文件名为database.xml。
阅读全文