2

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
  • 2
    What error you are getting? Also ; isnt necessary inside executeQuery Commented Oct 7, 2012 at 17:33

2 Answers 2

6

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

Sign up to request clarification or add additional context in comments.

Comments

-1

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

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

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.