springboot项目 java写一个工具类,查找出mysql数据库中其中一个库的所有表和字段和字段长度并生成一个xml文件
时间: 2023-05-23 22:02:12 浏览: 91
可以使用JDBC连接MySQL数据库获取数据库元数据信息,然后使用Java的XML生成库将元数据转换成XML文件。以下是实现代码的示例:
```java
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
public class DBMetadataToXMLTool {
public static void main(String[] args) throws IOException, SQLException, XMLStreamException {
String jdbcUrl = "jdbc:mysql://localhost:3306/mydb";
String jdbcUser = "username";
String jdbcPassword = "password";
String xmlFilePath = "/path/to/xmlfile.xml";
Connection conn = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection(jdbcUrl, jdbcUser, jdbcPassword);
DatabaseMetaData metadata = conn.getMetaData();
ResultSet tables = metadata.getTables(null, null, null, new String[] {"TABLE"});
List<String> tableNames = new ArrayList<>();
while (tables.next()) {
tableNames.add(tables.getString("TABLE_NAME"));
}
XMLOutputFactory factory = XMLOutputFactory.newInstance();
XMLStreamWriter writer = factory.createXMLStreamWriter(new FileWriter(new File(xmlFilePath)));
writer.writeStartDocument();
writer.writeStartElement("database");
for (String tableName: tableNames) {
ResultSet columns = metadata.getColumns(null, null, tableName, null);
writer.writeStartElement("table");
writer.writeAttribute("name", tableName);
while (columns.next()) {
String columnName = columns.getString("COLUMN_NAME");
String dataType = columns.getString("TYPE_NAME");
int columnSize = columns.getInt("COLUMN_SIZE");
writer.writeStartElement("column");
writer.writeAttribute("name", columnName);
writer.writeAttribute("type", dataType);
writer.writeAttribute("size", String.valueOf(columnSize));
writer.writeEndElement(); // column
}
writer.writeEndElement(); // table
}
writer.writeEndElement(); // database
writer.writeEndDocument();
writer.flush();
writer.close();
} catch (ClassNotFoundException | SQLException | IOException | XMLStreamException e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.close();
}
}
}
}
```
阅读全文