Fill JTable from database - java

I write this simple code to fill jTable1, but it just fills jTable1 with the last row from the database.
String SQL = "select * from usernames";
ResultSet rs = stmt.executeQuery(SQL);
String[] columnNames = {"Full Name", "Email"};
String n = "",e = "";
while(rs.next()) {
n = rs.getString("Full_Name");
e = rs.getString("Email");
Object[][]data = {{n,e}};
jTable1 = new JTable(data, columnNames);
}

I solved it by this code
String n = "",e = "";
DefaultTableModel model;
model = new DefaultTableModel();
jTable1 = new JTable(model);
model.addColumn("Full Name");
model.addColumn("Email");
while(rs.next())
{
n = rs.getString("Full_Name");
e= rs.getString("Email");
model.addRow(new Object[]{n,e});
}

Yes, it will always be the last row since in the while loop you are creating a new JTable instead of appending a row to the existing one. So do like this,
// Code
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
while(rs.next())
{
n = rs.getString("Full_Name");
e= rs.getString("Email");
//Object[][]data={{n,e}};
// This will add row from the DB as the last row in the JTable.
model.insertRow(jtable1.getRowCount(), new Object[] {n, e});
}

Related

Insert values from ArrayList into a JTable

public void populateJTable() {
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
Object[] rowData = new Object[4];
TrackService ts = new TrackService();
ArrayList<Track> tracks = ts.jsonToTracks();
for (int i = 0; i < tracks.size(); i++) {
rowData[0] = tracks.get(i).getTrackName();
rowData[1] = tracks.get(i).getArtist();
model.addRow(rowData);
}
jTable1 = new JTable(model);
}
In my json file I have stored metadata of an mp3 file which stores 5 values. My 'jsonToTracks' method stores them in an ArrayList.
I'm trying to get 2 of the values (trackName and artist) from inside my ArrayList and display them in my JTable.
My JTable has 4 columns - Name, Artist, Key, Mood. I'm trying to store the trackName and Artist in their corresponding columns. The Key and Mood column should be blank and the Name and Artist fields should be populated.
I can't see what I'm doing wrong, can anyone help?
Maybe you should try, moving your rowData initialization inside for loop.
public void populateJTable() {
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
TrackService ts = new TrackService();
ArrayList<Track> tracks = ts.jsonToTracks();
for (int i = 0; i < tracks.size(); i++) {
Object[] rowData = new Object[4];
rowData[0] = tracks.get(i).getTrackName();
rowData[1] = tracks.get(i).getArtist();
model.addRow(rowData);
}
jTable1 = new JTable(model);
}
jTable1 = new JTable(model);
I suspect the problem is that you are creating a new JTable but you never add the table to the frame.
Instead you should use:
jTable1.setModel( model );
This will replace the data in the existing JTable was I assume you have already added to a JScrollpane that has been added to the frame.

Binding jtable from mysql database in netbeans

I have almost finished my project and I'm getting stuck with displaying the Data from my DB into a Jtable. I have searched and read and still can't get this to work. I'm not displaying any errors but when I run the code I get an error when I click on search for the data. I get
java.sql.SyntaxErrorException: Syntax error: Encountered "INVENTORY"
at line 1, column 9. Does that mean my code is fine and its a problem with my Database?
Here is my code.
private void cmdSEARCHINVActionPerformed(java.awt.event.ActionEvent evt) {
ResultSet rs = null;
try {
String host = "jdbc:derby://localhost:1527/The_Home_Place";
String uName = "Lynn";
String uPass = "Lynn";
Connection con = DriverManager.getConnection( host, uName, uPass );
Statement stmt = con.createStatement();
String Query = "SELECT *INVENTORY";
rs = stmt.executeQuery(Query);
ResultSetMetaData rsmt = rs.getMetaData();
int col = rsmt.getColumnCount();
Vector column = new Vector(col);
for(int i = 1; i <= col; i++)
{
column.add(rsmt.getColumnName(i));
}
Vector data = new Vector();
Vector row = new Vector();
while (rs.next());
{
row = new Vector(col);
for(int i = 1; i <= col; i++){
row.add(rs.getString(i));
}
data.add(row);
}
//Create the Table
JFrame frame = new JFrame();
frame.setSize(500,120);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
JTable table = new JTable(data,column);
JScrollPane jsp = new JScrollPane(table);
panel.setLayout(new BorderLayout());
panel.add(jsp,BorderLayout.CENTER);
frame.setContentPane(panel);
frame.setVisible(true);
}
catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex.toString());
}
}
Your SQL query has invalid syntax. Try changing it to
String query = "SELECT * FROM INVENTORY";
instead. Also, you shouldn't be using Vector anymore, because the class is obsolete; use an ArrayList<String> (a generic collection, not a raw one) for storing the row data instead.

JTable displaying the same row from Mysql table

I'm showing the method were the JTable is constructed, the error is when adding the rows inside the for (int i = 1; i <= numero_columnas; i++) loop, or the way the DefaultTableModel model = new DefaultTableModel(); is declared, I can't find the error.
public void verTablaTable (Connection db, String nombre) throws Exception{
Statement stmt=db.createStatement();
ResultSet sst_ResultSet = stmt.executeQuery("SELECT * FROM "+nombre);
ResultSetMetaData md = sst_ResultSet.getMetaData();
int numero_columnas = md.getColumnCount();
DefaultTableModel model = new DefaultTableModel();
for (int i=1;i<=numero_columnas; i++){
model.addColumn(md.getColumnName(i));
}
JTable tabla =new JTable(model);
DefaultTableModel model1 = (DefaultTableModel) tabla.getModel();
Vector row = new Vector();
row.setSize(numero_columnas);
while (sst_ResultSet.next()){
for (int i = 1; i <= numero_columnas; i++){
row.set(i-1,sst_ResultSet.getString(i));
}
model1.addRow(row);
}
tabla.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
JScrollPane sp_vertabla = new JScrollPane(tabla);
sp_vertabla.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
sp_vertabla.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
sp_vertabla.setBounds(50,30,700,500);
JPanel cont_vertabla = new JPanel(null);
cont_vertabla.setPreferredSize(new Dimension(750,600));
cont_vertabla.add(sp_vertabla);
f_vertabla.setContentPane(cont_vertabla);
f_vertabla.pack();
f_vertabla.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
//f_vertabla.setResizable(false);
f_vertabla.setVisible(true);
f_vertabla.addWindowListener(this);
}
this is the way the JTable looks
The row listed in the above pic, is the last one in the mysql table
Try adding the line
Vector row = new Vector();
inside the while loop.

Loop only returns first row

Am trying to load the results of a database into a jtable, but when i run the code it only displays the first row and then errors an exception that no data was found. Here is my code;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + "C:\\Users\\PMatope.FMBMW.000\\Documents\\Library.accdb";
conn = DriverManager.getConnection(url, "", "");
st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT ID,full_name,sex,course,contact,email FROM Person");
ResultSetMetaData data = rs.getMetaData();
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
// jTable1.setModel(model);
while (rs.next()) {
String id,fname,sex,course,contact,email;
id = rs.getString("ID");
fname = rs.getString("full_name");
sex = rs.getString("sex");
course = rs.getString("course");
contact = rs.getString("contact");
email = rs.getString("email");
model.addRow(new Object[] {id,fname,sex,course,contact,email});
model.fireTableDataChanged();
JOptionPane.showMessageDialog(null, rs.getString("sex"));
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null,"Message: "+ e.getMessage());
}
Declare your table model first and create new instance for each loop times.
eg. :
DefaultTableModel model = null;
// jTable1.setModel(model);
while (rs.next()) {
model = (DefaultTableModel) jTable1.getModel();
String id,fname,sex,course,contact,email;
id = rs.getString("ID");
fname = rs.getString("full_name");
sex = rs.getString("sex");
course = rs.getString("course");
contact = rs.getString("contact");
email = rs.getString("email");
model.addRow(new Object[] {id,fname,sex,course,contact,email});
model.fireTableDataChanged();
JOptionPane.showMessageDialog(null, rs.getString("sex"));
}
You need to initialise,
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
inside your while loop

Using JTables in netbeans

I want to display the data out of my result set into a JTable.
When I run the following code the table doesn't update.
public void getHouses(int price) {
Connection conn;
ArrayList<Integer> ID = new ArrayList<Integer>();
ArrayList<String> Price = new ArrayList<String>();
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection("jdbc:odbc:Houses");
Statement statement = conn.createStatement();
ResultSet rec = statement.executeQuery("SELECT * FROM Houses WHERE Price <= " + price + "");
while (rec.next()) {
ID.add(rec.getInt("ID"));
Price.add(rec.getString("Price"));
}
String[] columnNames = {"House ID", "House Price"};
Object[][] rows = new Object[ID.size()][2];
for (int i = 0; i < ID.size(); i++) {
rows[i][0] = ID.get(i);
rows[i][1] = Price.get(i);
}
jTable1 = new JTable(rows, columnNames);
statement.close();
} catch (SQLException se) {
} catch (ClassNotFoundException cnf) {}
}
NOTE!
I added the JTable to the gui by drag and drop.
I also tested that my resultset has the data in it.
You need to learn about OP Swing MVC pattern, you need to declare a TableModel which your data store then set it to your table, like:
TableModel myData = new DefaultTableModel(columnVector, dataVector);
jTable1.setModel(myData);
Read more about DefaultTableModel

Categories