JTable doesn't show the newly inserted row/data - java

I have a JTable and I populte the table as follows:
jTable_Std_info.setModel(DBControler.getALLStudents());
And the following is a static method in a class named DBControler which retrieves all the data from the database(Oracle).
public static DefaultTableModel getALLStudents() throws SQLException, Exception {
DefaultTableModel tableModel = new DefaultTableModel();
Vector rows = new Vector();
Vector columns = new Vector();
try {
conn = geConnection();
cst = conn.prepareCall("{? = call std_getInfoFunc}");
cst.registerOutParameter(1, oracle.jdbc.OracleTypes.CURSOR);
cst.execute();
res = (ResultSet) cst.getObject(1);
System.out.print(res);
ResultSetMetaData rsm = res.getMetaData();
for (int i = 1; i <= rsm.getColumnCount(); i++) {
columns.addElement(rsm.getColumnName(i));
}
int row = 0;
while (res.next()) {
Vector vRow = new Vector(); //to store the current row
//System.out.println("Row " +row+"\n");
for (int i = 1; i <= rsm.getColumnCount(); i++) {
String columnValue = res.getString(i);
vRow.addElement(columnValue);
}
row += 1;
rows.addElement(vRow);
}
tableModel.setDataVector(rows, columns);
} catch (SQLException e) {
e.printStackTrace();
} finally {
res.close();
conn.close();
}
return tableModel;
}
So far everything works fine, but the problem is that if I insert a new record in the database, the JTable doesn't get the newly inserted row/data. Why is that and how can I fix this problem?
UPDATE:
It's retrieving the data when I commit my new insertion. So do I have to commit each time I update? Or is there any other ways to do this?

I think that you looking for Oracle Built-In Database Change Notification, not sure if is accesible for Oracle's in free-versions, if not then never mind, for MySQL is there two or three similair API for Java JDBC

But the problem is that if I insert a new record in the database, the JTable doesn't get the newly inserted row/data. Why is that?
The TableModel doesn't know when the database is updated.
and how can I fix this problem?
If your application is adding the row to the database then it also needs to add a row to the TableModel at the same time.

Related

Java UI - doesn't create and populate table

I am trying to pull data from a table in a mysql database and populate the results in a JTable. There are currently 3 tabs in the UI, the first two being input screens, which work fine. The 3rd tab, I am trying to run a query (after button is pushed) and display the results in a JTable. I am getting no error messages, but the screen does not display the table. Below is my code. Any assistance would be greatly appreciated. Note, user name and password have been replaced with generic. The query has also been simplified until I can get it to work. The system.out.print was just to check and see if it was pulling any data.
private void salePropertyActionPerformed(java.awt.event.ActionEvent evt) {
String sSelectQuery = "";
Statement statement=null;
Connection conn = null;
//PreparedStatement pStatement =null;
JPanel panel= spPanel;
TableColumn column;
JTable spTable = jTable1;
Vector columnNames = new Vector();
Vector data = new Vector();
spTable = new JTable(data,columnNames);
JScrollPane scrollPane = new JScrollPane(spTable);
panel.add(scrollPane);
try {
String myDriver = "com.mysql.jdbc.Driver";
String myURL = "jdbc:mysql://localhost:3306/realestate?autoReconnect=true&useSSL=false";
Class.forName(myDriver);
conn=DriverManager.getConnection(myURL,"root","jul1664bd");
/*Storing SQL statement*/
sSelectQuery ="SELECT propertyID, propertyPrice FROM property";
statement = conn.createStatement();
try (ResultSet rs = statement.executeQuery(sSelectQuery) //executes the query
) {
ResultSetMetaData metaData = rs.getMetaData();
int columns = metaData.getColumnCount();
for(int i = 1; i<=columns; i++){
columnNames.addElement(metaData.getColumnName(i));
}
while (rs.next()){
Vector row = new Vector(columns);
for (int i=1; i<=columns; i++){
row.addElement(rs.getObject(i));
}
data.addElement(row);
System.out.println(data);
}
rs.close();
for (int i=0; i<spTable.getColumnCount(); i++){
column=spTable.getColumnModel().getColumn(i);
//column.setMaxWidth(250);
}
}
statement.close();
} catch (SQLException e) {
System.err.println("An exception ocurred");
System.err.println(e.getMessage());
} catch (ClassNotFoundException ex) {
Logger.getLogger(realEstateUI.class.getName()).log(Level.SEVERE, null, ex);
}
JOptionPane.showMessageDialog(this,"Query Complete");
}
/**
You are attempting to add the JTable after the UI is visible. For the addition to take affect you must call revalidate followed by repaint. As an alternative, add your JTable upon UI construction (before it is visible) and populate the model of the JTable in salePropertyActionPerformed

ResultSet not open. Operation GetMetaData is not allowed

I got some problem with a database class, I have got 2 methods there. That supposed to fill JTable with data from database.
The problem is Im reciving errors (tittle). Here is my code:
public class QueryModel {
private Connection connection = null;
private ResultSet resultSet = null;
private Statement statement = null;
private ResultSetMetaData metaData = null;
public void sendStatement(CreateDataBase database,String query)
{
try
{
connection = database.getConnection();
}
catch (SQLException | ClassNotFoundException e)
{
System.err.println(e);
}
if (!query.equals(""))
{
try
{
statement = connection.createStatement();
resultSet = statement.executeQuery(query);
metaData = resultSet.getMetaData();
if (statement.execute(query))
{
System.out.println("Result:");
JTable table = new JTable(buildTableModel());
JOptionPane.showMessageDialog(null, new JScrollPane(table));
}
else
{
System.out.println("Executed!");
}
statement.close();
}
catch (SQLException e)
{
System.err.println(e);
}
}
}
public DefaultTableModel buildTableModel() throws SQLException
{
// names of columns
Vector<String> columnNames = new Vector<String>();
int columnCount = metaData.getColumnCount();
for (int column = 1; column <= columnCount; column++)
columnNames.add(metaData.getColumnName(column));
// data of the table
Vector<Vector<Object>> data = new Vector<Vector<Object>>();
while (resultSet.next())
{
Vector<Object> vector = new Vector<Object>();
for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++)
vector.add(resultSet.getObject(columnIndex));
data.add(vector);
}
return new DefaultTableModel(data, columnNames);
}
}
The problem seems to be getMetaData function in my opinion, without this every query goes smoothly. Problems started when I added this. I haven't been using this yet, so I do not know how to handle this, don't know if there is any sence to trying fixing it instead of doing this other way. Like more manually.
You are implicitly closing the first resultset when you execute the query for the second time in the "if" clause.
I mean, resultset is a pointer to an object defined in the executeQuery() and then you're redefining implicitly the resultset in the execute(query).
That's because you're querying twice.
Try defining metadata from inside your if block and see if it works (probably will)
Leo is right. The MetaData object comes from the first ResultSet which is closed when you re-execute the query. Don't execute the query twice, or if you have to, make sure you get a "fresh" MetaData object from the result set which you are actually navigating.

Cant display rows in a JTable (Values from Database)

Hello dear programmers,
it's my first post and i hope i'm able to describe which kind of problem i have.
I'm German, thats why my classnames are in german. I tried to put in some helpfull comments.
I'm trying to put the values of a database (called "buchungen") into a JTable inside a JPanel.
My JTable shows up but only the headers and no rows..
Here is my class with the JTable inside:
public class Verlauf extends SQL{
JTable table = new JTable();
DefaultTableModel model = new DefaultTableModel();
Verlauf(){
removeAll();
try {
rs = stmt.executeQuery("SELECT * FROM buchungen WHERE Ausführer = '" + kontoNr + "'"); // kontoNr equals to Ausführer in the database
} catch (Exception e) {
e.printStackTrace();
}
displayData(rs);
repaint();
}
public void displayData(ResultSet rs)
{
int i;
int count;
String a[];
String header[] = {"BuchungsNr","Ausführer","Betrag","Aktion","Empfänger"}; //Table Header Values, change, as your wish
count = header.length;
//First set the Table header
for(i = 0; i < count; i++)
{
model.addColumn(header[i]);
}
table.setModel(model); //Represents table Model
add(table.getTableHeader(),BorderLayout.NORTH);
a = new String[count];
// Adding Database table Data in the JTable
try
{
while (rs.next())
{
for(i = 0; i < count; i++)
{
a[i] = rs.getString(i+1);
}
model.addRow(a); //Adding the row in table model
table.setModel(model); // set the model in jtable
}
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, "Exception : "+e, "Error", JOptionPane.ERROR_MESSAGE);
}
}
I got the method for the jtable from a other post which i cant find anymore...
I hope someone can help me :)
Edit: The connection to my database is made in another class (called SQL) which works fine because i can use it from other classes perfectly in the same way i did here.
Greetings Lukas Warsitz
While the JTable header has been added to the container, the table itself has not
add(table);

Populate Java table with resultSet

I'm building a java application that gets its data from an oracle database and puts it into a JTable.
My problem is I am not able to populate the table, I don't understand how to do it. Javadoc is useless.
I don't understand why the table doesn't get the rows:
if ((report.getMsg()=="selectEventoAll") && (report.getEsito()==1))
{
DefaultTableModel dtm = new DefaultTableModel();
eventi_tb.setModel(dtm);
try
{
ResultSet res_eventi = report.getRes();
i = 0;
Object[][] datiEventi = new Object[report.getRowCount()][5];
while(res_eventi.next())
{
j = 0;
while (j < 5)
{
datiEventi[i][j] = res_eventi.getObject(j+2);
j++;
}
dtm.addRow(datiEventi[i]);
i++;
}
}
You can do this using a custom implementation of AbstractTableModel.
After you get your results back, put them in a list and let this be the backing list for your table model.
See here .. http://download.oracle.com/javase/tutorial/uiswing/components/table.html#data
Table From Database should get you started.

SQL data and JTable

I'm trying one sample program for practice and i want to display results of database in JTable. The problem is i have no idea how to do that. I know how to get data from database and display it on text field or console but never tried with JTable. How to do that ?
Consider that i've table which is holding information like person name, age, city and date. i want it to be displayed via JTable. Also is it possible to update the JTable display if i add the option of adding more details in program(i mean adding entries to db then that will show immediately in JTable )?
Any suggestions, pointers on how to proceed is appreciated. Thanks in advance.
JDBC + JTable # google:
Hacking Swing: A JDBC Table Model
Mastering the JTable
Making SQL Queries with JDBC and Displaying Results with Swing
here is the code
public static TableModel resultSetToTableModel(ResultSet rs) {
try {
ResultSetMetaData metaData = rs.getMetaData();
int numberOfColumns = metaData.getColumnCount();
Vector<String> columnNames = new Vector<String>();
// Get the column names
for (int column = 0; column < numberOfColumns; column++) {
columnNames.addElement(metaData.getColumnLabel(column + 1).toUpperCase());
}
// Get all rows.
Vector<Vector<Object>> rows = new Vector<Vector<Object>>();
while (rs.next()) {
Vector<Object> newRow = new Vector<Object>();
for (int i = 1; i <= numberOfColumns; i++) {
newRow.addElement(rs.getObject(i));
}
rows.addElement(newRow);
}
return new DefaultTableModel(rows, columnNames);
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
you can call this method such that way
void update_Table() throws ParseException
{
// we used this try catch so that values in table automatically show(without clicking on any button) when the dialog box open
try
{
Connection con=MSUTIL.getMSConnection();
PreparedStatement pst=con.prepareStatement("select payment_mode from PaymentMode");
ResultSet rs=pst.executeQuery();
//here i call that method
table.setModel(resultSetToTableModel(rs));
table.getTableHeader().setFont(new Font("SansSerif", Font.BOLD, 14));
while(rs.next())
{
mp.paymentmode_ComboBox.addItem(rs.getString("payment_mode"));
}
}
catch(SQLException e)
{
e.printStackTrace();
}
finally
{
//this method is for closing the connection
MSUTIL.cleanUp(con, pst, rs);
}
}

Categories

Resources