日期:2014-05-16  浏览次数:20778 次

怎样在程序中列出MySQL实例的数据库和表?
我想在java程序中列出某个MySQL实例下的数据库和表,比如像MySQL的ODBC配置程序那样的.

------解决方案--------------------
之前将mysql的JDBC驱动程序放到库路径中。

比如:
import java.sql.*;

public class GetMysqlDatabaseName {
public static void main(String[] args){
try{
Connection conn;
Statement stmt;
ResultSet res;

// 创建一个连接
Class.forName( "com.mysql.jdbc.Driver ").newInstance();
conn = DriverManager.getConnection(
"jdbc:mysql://localhost/zhxsqlstudy ", "user ", "username "
);

// 执行show databases,返回结果保存在res中
stmt = conn.createStatement();
res = stmt.executeQuery( "show databases ");

// 将数据库名称打印出来。至于怎么处理随你高兴。
while (res.next()){
String databaseName = res.getString( "Database ");
System.out.println( "Database " + databaseName);
}

res.close();
} catch(Exception e){
System.out.println( "Error " + e.toString());
}
}
}