I have a frame with table,combobox, i want to fill the table with data from database by combobox, but if i use with itemlistener i dont see the table, without itemlistener and String sql="select * from Arlista"
then i see my table with data
(combob=combobox)
combob.addItemListener(new ItemListener(){
@Override
public void itemStateChanged(ItemEvent e){
tesztvalt=(combob.getSelectedItem()).toString();
if (e.getItem().equals(tesztvalt))
{
try {
Class.forName( driver );
Connection connection = DriverManager.getConnection( url );
String sql="select * from "+tesztvalt+"";
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery( sql );
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
while (rs.next()) {
Vector row = new Vector(columns);
for (int i = 1; i <= columns; i++)
{
row.addElement( rs.getObject(i) );
}
data.addElement( row );
}
rs.close();
stmt.close();
connection.close();
}catch(Exception ex) {
System.out.println( e );
}
JTable table = new JTable(data, columnNames)
{
public Class getColumnClass(int column)
{
for (int row = 0; row < getRowCount(); row++)
{
Object o = getValueAt(row, column);
if (o != null)
{
return o.getClass();
}
}
return Object.class;
}
};
JScrollPane scrollPane = new JScrollPane( table );
getContentPane().add( scrollPane );
JPanel buttonPanel = new JPanel();
getContentPane().add( buttonPanel, BorderLayout.SOUTH );
}
}
});
String sql="SELECT * FROM "+tesztvalt+"";
PreparedStatement pst = conn.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
while (rs.next())
{
tabla.setModel(model);
}
You have a couple of problems:
You are using the PreparedStatement
incorrectly. Your code may work (I'm not sure), but it does not take advantage of the features of the PreparedStatement
.
The code that read the data from the ResultSet makes no sense because, well you aren't even reading any data from the ResultSet.
To use a PreparedStatement the code is something like:
String sql = "Select * from ?";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString( 1, tesztvalt );
stmt.executeQuery();
Now the PreparedStatement will build the SQL query with the proper delimiters so you don't need to worry about that.
Read the section from the JCBC tutorial on Using Prepared Statements for more information.
If you want to read all the data from a specific table, then check out the TableFromDatabaseExample.java
code found in Table From Database. It shows how to build the query as well as how to access the column names and data.