用 JDBC 列出 mySQL 数据库的结构(0分)

  • 主题发起人 主题发起人 yysun
  • 开始时间 开始时间
Y

yysun

Unregistered / Unconfirmed
GUEST, unregistred user!
//下面这个 Java 程序可以输出 mySQL 数据库的结构(Tables + Fields)到 XML
import java.text.*;
import java.util.*;
import java.sql.*;
public class DBTables {
String sDBDriver = "org.gjt.mm.mysql.Driver";
String sDbUser = "yysun";
String sDbPass = "******";
String sDatabase = "lgc";
String sConnStr = "jdbc:mysql://localhost/" + sDatabase;
private Connection conn = null;
public DBTables(){
try {
Class.forName(sDBDriver);
}
catch(java.lang.ClassNotFoundException ex) {
System.err.println(ex.getMessage());
}
}
public void listFields(String table) {
Statement stmt = null;
ResultSet rs = null;
System.out.println("<" + table + ">");
try {
String sql = "select * from " + table;
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
for (int ii = 1;
ii <= rs.getMetaData().getColumnCount();
ii++) {
String field = rs.getMetaData().getColumnName(ii);
System.out.print("<" + field + ">");
System.out.print(rs.getMetaData().getColumnTypeName(ii));
System.out.println("</" + field + ">");
}
}
catch(SQLException ex) {
System.err.println(ex.getMessage());
}
System.out.println("</" + table + ">");

}

public void listTables() {
DatabaseMetaData md = null;
ResultSet rs = null;
try {
conn = DriverManager.getConnection(sConnStr, sDbUser, sDbPass);
md = conn.getMetaData();
rs = md.getTables(sDatabase, sDbUser, "%", null);
if (rs != null) {
System.out.println("<?xml version=/"1.0/"?>");
System.out.println("<" + sDatabase + ">");
while (rs.next()) {
String table = rs.getString(3);
listFields(table);
}
System.out.println("</" + sDatabase + ">");
rs.close();
}
}
catch(SQLException ex) {
System.err.println(ex.getMessage());
}
}
public static void main(String[] args) {
new DBTables().listTables();
}
}
 
^_^
这个我们自己已经写过啦
顺便说一句,自动生成代码,这个就是基础部分呀。我们都做过啦。
 
后退
顶部