在这里依赖一个类DatabaseMetaData,这个对象可以从数据库连接来获取。有了它万事大吉了,想知道什么问它即可:
//获取所有表
ResultSet tableSet = databaseMetaData.getTables(null, "%", "%", new String[]{"TABLE"});
//获取所有列
ResultSet columnSet = dbmt.getColumns(null, "%", tableName, "%");
//获取列个数
int numberOfColumns = rsmd.getColumnCount();
下面就是如何从数据库读取表信息了。
引入 jdom2的相关JAR文件,数据库自己选择(这里我用的是PostgreSQL数据库)
//数据库连接
public class DataBaseUtil {
private static Connection conn = null;
@SuppressWarnings("unchecked")
public static Connection getConn() throws ClassNotFoundException, SQLException
{
if (conn==null)
{
Class.forName("org.postgresql.Driver");
String url = "jdbc:postgresql://localhost:5432/postgis" ;
conn = DriverManager.getConnection(url, "postgres" , "12345" );
}
return conn;
}
}
//生成XML格式
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.XMLOutputter;
public class getDBStructure {
/**
* @param args
* @throws SQLException
* @throws ClassNotFoundException
*/
public static void main(String[] args) throws SQLException, ClassNotFoundException {
// TODO Auto-generated method stub
DataBaseUtil db = new DataBaseUtil();
DatabaseMetaData dbmt;
dbmt = db.getConn().getMetaData();
Statement st = db.getConn().createStatement();
ResultSet tableSet = dbmt.getTables(null, "%", "%", new String[]{"TABLE"});
Element root = new Element("POSTGIS_DB_XML");
root.setAttribute("VERSION","1.0");
Document Doc = new Document(root);
Element elements = new Element("Tables");
Element elementtable =null;
while (tableSet.next()){
String tableName = tableSet.getString(3); //获取数据库中表名称
elementtable = new Element("table");
elementtable.setAttribute("tableName",tableName );
ResultSet columnSet = dbmt.getColumns(null, "%", tableName, "%");
ResultSetMetaData rsmd = columnSet.getMetaData();
int numberOfColumns = rsmd.getColumnCount();//表中列个数
Element elementcolumn =null;
while(columnSet.next()){
String columnName = columnSet.getString("COLUMN_NAME");//获取列名称
String TYPE_NAME = columnSet.getString("TYPE_NAME"); //列字段类型
elementcolumn = new Element("column");
elementcolumn.setAttribute("columnName", columnName);
elementcolumn.setAttribute("TYPE_NAME", TYPE_NAME);
elementtable.addContent(elementcolumn);
}
elements.addContent(elementtable);
}
root.addContent(elements);
XMLOutputter XMLOut = new XMLOutputter();
String xml = XMLOut.outputString(Doc);
System.out.println(xml);
}
}