JDBC is not executing SHOW DATABASES command

2019-04-13 16:53发布

问题:

i want to get a list of databases stored in mysql and put in java table using command "show databases" via a resultset. but its not working.

DefaultTableModel model=(DefaultTableModel)dbTbl.getModel();
try{
    Class.forName("com.mysql.jdbc.Driver");
    Connection con=DriverManager.getConnection("jdbc:mysql//localhost/:3306","root","password");
    Statement stmt=con.createStatement();
    ResultSet rs=stmt.executeQuery("show databases;");
    while(rs.next())
   {
    String db=rs.getString(1);
    model.addRow(new Object[] {db});
   }
    rs.close();
    stmt.close();
    con.close();
}
catch(Exception e)
{
    JOptionPane.showMessageDialog(null,"nahi chalda");
}

回答1:

That's not the best way to get a list of Databases in JDBC. Here's the way it's done - using MetaData

Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/:3306","root","password");
DatabaseMetaData meta = con.getMetaData();
ResultSet resultSet = meta.getCatalogs();
while (resultSet.next()) {
   String db = resultSet.getString("TABLE_CAT");
   model.addRow(new Object[] {db});
}
resultSet.close();
con.close();

See also: how to get list of Databases "Schema" names of MySql using java JDBC



回答2:

I just forgot to add colon after "jdbc:mysql Correct code is:

Connection con=DriverManager.getConnection("jdbc:mysql://localhost/:3306","root","password");

It works ,......... !!!