import java.sql.*;
import java.io.*;
import java.util.Vector;    
import javax.swing.*;
import javax.swing.table.*;

public class QueryTableModel extends AbstractTableModel
{
 Vector cache;
 int colCount;
 String[] headers;
 Connection db;
 Statement statement;
 String currentURL;

 public QueryTableModel()
 {
  cache=new Vector();
 }

 public String getColumnName(int i) {return headers[i];}
 public int getColumnCount() {return colCount;}
 public int getRowCount() {return cache.size();}

 public Object getValueAt(int row,int col)
 {
  return ((String[])cache.elementAt(row))[col];
 }

 public void setHostURL(String url)
 {
   if(url.equals(currentURL))
   {return;}
   closeDB();
   initDB(url);
   currentURL=url;
 }

 public void setQuery(String q)
 {
 cache= new Vector();
 try{
    ResultSet rs=statement.executeQuery(q);
    ResultSetMetaData meta=rs.getMetaData();
    colCount=meta.getColumnCount();
    headers=new String[colCount];
    for (int h=1;h<=colCount;h++)
      {
      headers[h-1]=meta.getColumnName(h);
      }
    while(rs.next())
      {
      String[] record=new String[colCount];
      for(int i=0;i<colCount;i++)
        {record[i]=rs.getString(i+1);}
      cache.add(record);
      } //while'in sonu
    fireTableChanged(null);
    } //try'in sonu
    catch(Exception e)
    {
    cache=new Vector();
    e.printStackTrace();
    }
 } // setQuery sonu

 public void initDB(String url)
 {
 try {
     db=DriverManager.getConnection(url);
     statement=db.createStatement();
     }
     catch(Exception e)
     {
       System.out.println("DataBase can not be started");
       e.printStackTrace();
     }
 } //initDB sonu

 public void closeDB()
 {
   try {
       if(statement!= null) {statement.close();}
       if(db != null) {db.close();}
       }
       catch(Exception e)
       {
       System.out.println("database is not closed");
       e.printStackTrace();
       }
 }  //closeDB sonu

}
