日期:2014-05-20  浏览次数:20808 次

如何通过JAVA的API得到数据库里面的表
我想通过JAVA的API返回该数据库所有的的表的名称。
应该是把“SHOW   TABLES;”这样的命令传给mysql,我应该通过怎样的API去做这个?
Statement.executeQuery嘛还是其他的?

或者有别的方法?

------解决方案--------------------
Connection con = ...;
DatabaseMetaData meta = con.getMetaData();
ResultSet rs = meta.getTables(null, null, null, null);
while(rs.next()) {
  System.out.println(rs.getString( "TABLE_NAME "));
}

rs 有许多列,具体的列说明可以参考 java.sql.DatabaseMetaData.getTables() 的 API 帮助。

------解决方案--------------------
<%@ page language= "java " contentType= "text/html; charset=GB2312 " pageEncoding= "GB2312 "%>
<%@page import= "java.util.Date "%>
<html>
<head>
<title> WEBLOGIC 9 INDEX </title>
</head>
<body>
<P align= "center "> <font size=7> <b> WEBLOGIC 9 INDEX </b> </font>
<%@page import= "java.sql.* " %>
<%@page import= "java.text.* " %>
<%
String time=DateFormat.getDateTimeInstance().format(new java.util.Date());
out.println( " <P> 当前时间: "+time);
//-----------------------------------------------
int i=0;
if(application.getAttribute( "count ")==null){
application.setAttribute( "count ",i);
}else{
i=new Integer(Integer.valueOf(application.getAttribute( "count ").toString()));
i++;
application.setAttribute( "count ",i);
}
out.println( " <P> 浏览次数: "+i);
//------------------------------------------------
String dbname=request.getParameter( "dbname ");
if(dbname==null){
out.println( " <P> 数据库名列表: <P> ");
try{
Class.forName( "com.mysql.jdbc.Driver ");
Connection con=DriverManager.getConnection( "jdbc:mysql://localhost/shujuku?user=root&password=mfditfyu&useUnicode=true&characterEncoding=GB2312 ");
DatabaseMetaData dmd=con.getMetaData();
ResultSet rs=dmd.getCatalogs();
int m=0;
while(rs.next()){
m++;
String dbn=rs.getString( "TABLE_CAT ");
out.println( " <a href=index.jsp?dbname= "+dbn+ "> "+m+ ". "+dbn+ " </a> &nbsp;&nbsp;&nbsp;&nbsp; ");
}
rs.close();
con.close();
}catch(Exception e){
out.println( "数据库服务未启动 "+e);
}
}else{
String tablename=request.getParameter( "tablename ");//获取表名
if(tablename==null){//如果没有表名就把表查出来
out.println( " <P> <b> "+dbname+ "库中表列表: </b> &nbsp;&nbsp; ");
out.println( " <a href=index.jsp> 主页 </a> <P> ");
try{
Class.forName( "com.mysql.jdbc.Driver ");
Connection con=DriverManager.getConnection( "jdbc:mysql://localhost/ "+dbname+ "?user=root&password=mfditfyu&useUnicode=true&characterEncoding=GB2312 ");
DatabaseMetaData dmd=con.getMetaData();
ResultSet rs=dmd.getTables(null,null,null,null);
int x=0;
while(rs.next()){
x++;
String tbname=rs.getString( "TABLE_NAME ");
out.println(x+ ". <a href=index.jsp?dbname= "+dbname+ "&tablename= "+tbname+ "> "+tbname+ " </a> &nbsp;&nbsp;&nbsp;&nbsp; ");
}
rs.close();
con.close();

}catch(Exception e){
out.println(dbname+ "未知错误: "+e);