inserting values from 2 mysql tables to single jtable row - java

I'm new to java. currently trying to make a program which manipulates with data from mysql. I have several tables in mysql and I need to add data to a single jtable row from 2 mysql tables. Now I'm getting data in different rows. Below my code for one table. Any suggestions how to change it?
public void fill_rs_table_test(){
DefaultTableModel model = new DefaultTableModel();
model.setColumnIdentifiers(new String[] {"rs_name","rs_number","firm_id"});
try{
String sql = "select * from inf_rs";
theView.pst = theView.conn.prepareStatement(sql);
theView.rs = theView.pst.executeQuery();
while(theView.rs.next()){
String rs_name = theView.rs.getString ("rs_name");
String rs_number = theView.rs.getString ("rs_number");
String firm_id = theView.rs.getString ("firm_id");
model.addRow(new Object[] {rs_name, rs_number,firm_id});
}
}
catch (Exception e){
}
this.theView.rs_table.setModel(model);
for (int i = 0, x = 0; i < theView.rs_table.getColumnModel().getColumnCount(); i++)
this.theView.rs_table.getColumnModel().getColumn(i).setCellEditor(new javax.swing.table.TableCellEditor(){
#Override
public boolean isCellEditable(java.util.EventObject anEvent) {
return false;
}
});

Related

Get Multiple columns in Result Set from sparql in Netbeans JTable

I am trying to select multiple columns in Jena result set and then binding the same to Java table.
When I select only one column, the result set is working fine but when I select two columns then the result set does not have any row although it has only columns:
Here is my Java code:
private void btnExecuteSPARQLActionPerformed(java.awt.event.ActionEvent evt) {
try
{
System.out.println("Executing SPARQL..."); // get the name list query
String queryString;
queryString = "PREFIX ssuet:<http://www.semanticweb.org/alinaanjum2/ontologies/2021/6/untitled-ontology-4#> "
+ txtQuery.getText();
com.hp.hpl.jena.query.ResultSet results = OpenOWL.ExecSparQl(queryString); //all method ExecSparQl from OpenOWL class
ResultSetFormatter.out(results);
// It creates and displays the table
JTable table = new JTable(buildTableModel(results));
JOptionPane.showMessageDialog(null, new JScrollPane(table));
}
catch (Exception ex)
{
System.out.println(ex);
}
}
//CODE ADDITION BY ALINA ANJUM STARTED ON 03-AUGUST-2021
public static DefaultTableModel buildTableModel(com.hp.hpl.jena.query.ResultSet rs)
throws SQLException {
List<String> metaData = rs.getResultVars();
// names of columns
Vector<String> columnNames = new Vector<String>();
int columnCount = metaData.size();
System.out.println(columnCount);
for (int column = 0; column <columnCount; column++)
{
columnNames.add(metaData.get(column));
}
// data of the table
Vector<Vector<Object>> data = new Vector<Vector<Object>>();
while (rs.hasNext())
{
QuerySolution sol = rs.nextSolution();
Vector<Object> vector = new Vector<Object>();
for (int columnIndex = 0; columnIndex < columnCount; columnIndex++)
{
//vector.add(rs.getObject(columnIndex));
String columnName = columnNames.get(columnIndex);
vector.add(sol.getLiteral(columnName).getString());
}
data.add(vector);
}
return new DefaultTableModel(data, columnNames);
}
The following Query is Perfectly returning values:
SELECT (str(?x) as ?name)
WHERE {
?Person ssuet:hasname ?x.
}
The following Query is working fine in Protege but not returning values in Result Set in Java:
SELECT (str(?x) as ?name)
(str(?y) as ?phone)
WHERE {
?Person ssuet:hasname ?x.
?Person ssuet:hasPhoneNumber ?y.
}
Screen shot of the OutPut in Netbeans:
Results for 2nd Query in protege:
ResultSets are iterators.
Calling ResultSetFormatter.out(results) exhausts the iterator (no more rows).
If you want to use the result twice, use ResultSetFactory.makeRewindable to get a result set that can be reset to the start.

JTable - Filter data

I'm trying to filter a JTable but the results are not as expected.
Below is the JTable with the added elements (I'm using MySQL to store the Data)
JTable with contents - Picture
When I try to filter the list for someone specific, I do not get the data from the table. For example, I search for "Ana" and nothing appears.
Search results for "Ana" - Picture
If I try to search using some "numbers", like the salary, I get the right result but the ID is not right. Pictures to clarify the issue below.
Wrong ID
Right ID
The Code to generate the ArrayList with the employees :
public static ArrayList<Angajat> listaAngajati() {
ArrayList<Angajat> listaAngajati = new ArrayList<>();
try (java.sql.Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/angajati", "root", "***");) {
Statement st = conn.createStatement();
st.executeQuery("select * from angajati");
ResultSet rs = st.getResultSet();
Angajat angajat;
while (rs.next()) {
angajat = new Angajat(rs.getInt("id"), rs.getString("nume"), rs.getString("prenume"), rs.getInt("varsta"), rs.getString("adresa"), rs.getDouble("salariu"));
listaAngajati.add(angajat);
}
} catch (SQLException ex) {
System.out.println("Error in database connection: \n" + ex.getMessage());
}
return listaAngajati;
}
public static void arataAngajati() {
ArrayList<Angajat> arataAngajati = listaAngajati();
DefaultTableModel model = (DefaultTableModel) tabelangajati.getModel();
Object[] rand = new Object[6];
for (int i = 0; i < arataAngajati.size(); i++) {
rand[0] = arataAngajati.get(i).getID();
rand[1] = arataAngajati.get(i).getNume();
rand[2] = arataAngajati.get(i).getPrenume();
rand[3] = arataAngajati.get(i).getVarsta();
rand[4] = arataAngajati.get(i).getAdresa();
rand[5] = arataAngajati.get(i).getSalariu();
model.addRow(rand);
}
}
Code to filter the JTable
private void cautaInTabelKeyReleased(java.awt.event.KeyEvent evt) {
DefaultTableModel tabel = (DefaultTableModel) tabelangajati.getModel();
String query = cautaInTabel.getText().toLowerCase();
TableRowSorter<DefaultTableModel> sort = new TableRowSorter<DefaultTableModel>(tabel);
tabelangajati.setRowSorter(sort);
sort.setRowFilter(RowFilter.regexFilter(query));
}
Question : How can I modify the code so when I try to search for a an employee using his name to get the right result (not like now - no results) and when trying to modify the employee data, to get the right ID as shown in the JTable (example in the pictures above) ?
EDIT
In order to filter the data from the table accordingly I had to use
sort.setRowFilter(RowFilter.regexFilter("(?i)" + query));
When I was filtering the table, only the view modified and not the values from the row (Even if I saw the values from the row 3 and values on the backend where from the row 1). I managed to modify the following row and the table works perfectly.
From :
int row = tabelangajati.getSelectedRow();
To :
int row = tabelangajati.convertRowIndexToModel(tabelangajati.getSelectedRow());

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);

JAVA update database on JTable cell change

He I am noob to Java (Thats not new) and I can't find a good tutorial for this. I use jTable to display a table filled with data from a MySQL database.
So far so good, I get the table:
Standard you can click a table cell and it changes to a text-field with can be filled with something new. You all know that, but how can I use this to also update the value in my database?
My code:
import [...];
public class table extends JPanel {
public String table;
private Database db;
public table(String tablename, Database db){
try {
table = tablename;
this.db = db;
//Get table with and height
ResultSet res = db.query("SELECT COUNT( * ) FROM `"+table+"`");
ResultSet res2 = db.query("SELECT COUNT( * ) FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = '"+table+"'");
int rows = 0;
int collums = 0;
res.next();
res2.next();
rows = res.getInt(1);
collums = res2.getInt(1);
//Get table column names and set then in array
ResultSet clom = db.query("DESCRIBE `"+table+"`");
String[] columnNames = new String[collums];
int s = 0;
while(clom.next()){
columnNames[s] = clom.getString(1);
s++;
}
//get table data and put in array
Object[][] data = new Object[rows][collums];
ResultSet result = db.query("SELECT * FROM `"+table+"`");
int q = 0;
while(result.next()){
for(int a=0; a<= (collums - 1); a++){
data[q][a] = result.getString(a + 1);
//System.out.println(q + " - " + a);
}
q++;
}
//Make Jtable of the db result form the two array's
final JTable table = new JTable(data, columnNames);
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.setFillsViewportHeight(true);
// do some event listening for cell change
JScrollPane scrollPane = new JScrollPane(table);
JFrame frame = new JFrame("table editor");
scrollPane.setOpaque(true);
frame.setContentPane(scrollPane);
frame.pack();
frame.setSize(600, 800);
frame.setVisible(true);
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
I guess I need to bind some kind of table listener and when something changes I take all the values of the table and update them with a query.
How can I do this?
This is my pseudo code:
table.bindCellEventListner(callback(t){
Array row = t.getAllValuesAsArrayOfRow();
String data = "";
int f = 0
while(row.next()){
data .= "`"+clom[f]+"` = '"+row[f]+"',"
f++;
}
data.delLastChar();
db.query("UPDATE `"+table+"` SET "+data+" WHERE `id` ="+row[0]+";");
});
A deleted answer plagiarised Rachel Swailes' answer from 14 years ago, found here. For completeness and because the answer is correct and useful, I have quoted the relevant text here:
Step 1: It's going to be way easier for the whole thing if you make your table extend a TableModel from now (if you haven't already). So if you need help with that just ask.
Step 2: In the table model you need to enable the cells to be editable. In the TableModel class that you make, you need to add these methods
public boolean isCellEditable(int row, int col) {
return true;
}
public void setValueAt(Object value, int row, int col) {
rowData[row][col] = value;
fireTableCellUpdated(row, col);
}
Step 3: You will see in the second method that we fire a method called fireTableCellUpdated. So here we can catch what the use it changing. You need to add a TableModelListener to your table to catch this.
mytable.getModel().addTableModelListener(yourClass);
And in the class that you decide will implement the TableModelListener you need this
public void tableChanged(TableModelEvent e) {
int row = e.getFirstRow();
int column = e.getColumn();
TableModel model = (TableModel)e.getSource();
Object data = model.getValueAt(row, column);
...
}
now you have the data in the cell and the place in the grid where the
cell is so you can use the data as you want

JTable doesn't show the newly inserted row/data

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.

Categories

Resources