0

I'm trying to create a table and add values to sql by using table in java swing. But in for loop i doesn't incrementing at all. I think its because of while(rs2.next()).When i place it out of for loop i get this error: "Before start of result set". I need help!

EDIT: Those problems above is handled but i have new problem now. It seems like JTable not updating itself. When i chose a table name in combobox table application crashes and give array index out of bounds exception.

My code is here:

public class DBC extends JFrame{

static String tablo;
static JTextField tf = new JTextField(20);
static int columnCount;
static JPanel tfPanel = new JPanel();
static String[] sutunlar;
static JLabel sutunLabel;
static JPanel sutunPanel = new JPanel(new BorderLayout());
static JTable table;
static JScrollPane scrollPane;

public static void main(String[] args) throws Exception {

    Class.forName("com.mysql.jdbc.Driver");
    Connection connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/project"
              ,"root","123456789");

    final Statement statement = connect.createStatement();

    JLabel tabloSec = new JLabel("Tablo Seçin:");
    final JComboBox<String> tablolar = new JComboBox<String>();
    final DatabaseMetaData md = connect.getMetaData();
    final ResultSet rs = md.getTables(null, null, "%", null);

    while (rs.next()) {
        tablolar.addItem(rs.getString(3));
    }

    tablolar.addActionListener(new ActionListener(){

        @Override
        public void actionPerformed(ActionEvent arg0) {

            tablo = tablolar.getSelectedItem().toString();

            try {

                 ResultSet rs2 = statement.executeQuery("SELECT * FROM "+tablo);
                 ResultSetMetaData rsmd = rs2.getMetaData();
                 columnCount = rsmd.getColumnCount();

                 sutunlar = new String[columnCount];
                 table = new JTable(1,columnCount);
                 Object columnNames[] = new Object[columnCount];
                 Object rowData[][] = {{""}};

                     for(int i=0;i<columnCount;i++){

                         sutunlar[i] = rsmd.getColumnLabel(i+1);
                         columnNames[i] = sutunlar[i];

                         }

                     table = new JTable(rowData, columnNames);
                     table.repaint();
                     scrollPane = new JScrollPane(table);
                     sutunPanel.add(scrollPane);
                     sutunPanel.revalidate();

            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    });

    JButton ekle = new JButton("Ekle");
    ekle.addActionListener(new ActionListener(){

        @Override
        public void actionPerformed(ActionEvent e) {

            try {
                switch(tablo){
                case "department":

                    statement.executeUpdate("INSERT INTO department(Name,Location) VALUES('"+tf.getText()+"')");
                case "employee":

                    statement.executeUpdate("INSERT INTO employee(Id,FirstName,LastName,Sex,Address,Email,Salary,BirthDate,JoinDate) VALUES('"+tf.getText()+"')");
                case "engineer":

                    statement.executeUpdate("INSERT INTO engineer(EngineerType) VALUES('"+tf.getText()+"')");
                case "manager":

                    statement.executeUpdate("INSERT INTO manager(Department) VALUES('"+tf.getText()+"')");
                case "project":

                    statement.executeUpdate("INSERT INTO project(Name,Number,Value) VALUES('"+tf.getText()+"')");
                case "secretary":

                    statement.executeUpdate("INSERT INTO secretary(TypingSpeed) VALUES('"+tf.getText()+"')");
                }

            } catch (SQLException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }
    });

    JButton cik = new JButton("Çık");
    cik.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            System.exit(0);
        }
    });

    JPanel panel = new JPanel(new FlowLayout());

    panel.add(tabloSec);
    panel.add(tablolar);
    panel.add(sutunPanel);
    panel.revalidate();
    panel.add(ekle);
    panel.add(cik);

    JFrame frame = new JFrame("Deneme");
    frame.setSize(600,600);
    frame.setLocationRelativeTo(null);
    frame.add(panel);
    frame.setVisible(true);
  }
}
Miral
  • 403
  • 5
  • 13
  • 30
  • Why are you looping on the number of columns? With the `while` you already go through all the rows returned. – Sotirios Delimanolis Mar 25 '13 at 14:22
  • I want to get column names in specific table. So, if that table has 3 columns i have to get in the loop 3 times. Am i wrong? – Miral Mar 25 '13 at 14:24
  • What is the value of columnCount? – Achintya Jha Mar 25 '13 at 14:24
  • Actually there is some mistake at columnCount to. It's value now 23 but 23 is the all columns in database. I want column count in specific table but it doesn't important because set is taking care of null values. – Miral Mar 25 '13 at 14:28
  • 1
    `tablo` should probably be `rs.getString(2) + "." + rs.getString(3)`. – trashgod Mar 25 '13 at 20:54

2 Answers2

0

I dont think there is problem with for loop.

while(rs2.next()){

}

When this one get executed once the condition is being false for other iteration of i and it dont enter while loop.

If you want to test you can do :

for(int i=0;i<columnCount;i++){  

    while(rs2.next()){              

       sutunlar[i] = rs2.getString(4);
       Set<String> setSutunlar = new HashSet<>(Arrays.asList(sutunlar[i]));
       Object rowData[][] = {null};
       Object columnNames[] = setSutunlar;
       table = new JTable(rowData, columnNames);
       scrollPane = new JScrollPane(table);
       sutunPanel.add(scrollPane);
    }

    System.out.println("Value of i is " + i);// Add this line to check iteration of i.
}
Achintya Jha
  • 12,735
  • 2
  • 27
  • 39
  • This is what i have coded before i write here. I checked i in debug mode and when its come in while loop i becomes 0 again. – Miral Mar 25 '13 at 14:43
  • @Miral How can it be possible. I think your while loop getting executed only once when value of i is zero after that rs.next() becomes fales and it dont enters while loop. – Achintya Jha Mar 25 '13 at 14:49
0

I think you mixed something up. When you define

columnCount = rsmd.getColumnCount();

It seems you expect that columnCount holds the number of columns of the table; but this is not the case. This is the number of columns the metadata provides.

If you want to fetch the names of the columns of the selected table, put this in your try/catch block:

ResultSet rs2 = md.getColumns(null, null, tablo, null);

Set<String> columnNames = new HashSet<String>();
while (rs2.next()) {
  columnNames.add(rs2.getString(4));
}

Object[][] rowData = { null };
table = new JTable({ null }, columnNames.toArray());
scrollPane = new JScrollPane(table);
sutunPanel.add(scrollPane);

And you should really think about your usage of static fields ;)

skirsch
  • 1,640
  • 12
  • 24