I am working on a java project
I am using jdk 1.6
I am want to add data from database in jtable
I have achieved this by using DefaulTableModel
and I got the column names by using ResultSetMetadata
but the problem is
**I am getting a extra column name A at the 0th index of jtable
I want to remove this column
it looks like this
A | deptno
I only need deptno
**
the code used for creating this model is
private void updateTable() throws Exception {
String sqlrow = "Select count(*) from emp";
rs= db.sta.executeQuery(sqlrow);
rs.next();
int rows=rs.getInt(1);
System.out.println(""+rows);
String sqldata = "SELECT deptno FROM emp";
rs =db.sta.executeQuery(sqldata);
rsMD = rs.getMetaData();
numberOfColumns = rsMD.getColumnCount();
ColumnNames = new String[numberOfColumns+1];
System.out.println(""+numberOfColumns);
for(int i=1;i<=numberOfColumns;i++)
{
String colName=rsMD.getColumnName(i);
ColumnNames[i] = colName;
System.out.println(""+ColumnNames[i]);
}
//Cj is a method which takes sqlQuery , rows, column
Object[][] rowData=CJ(sqldata,rows,numberOfColumns);
//jt is table name
jt.setModel(new DefaultTableModel(rowData,ColumnNames));
}
// code for cj()
public Object[][] CJ(String sql,int rows,int cols)
{
Object[][] obj=new Object[rows][cols+1];
ResultSet rs=null;
try{
rs= db.sta.executeQuery(sql);
int c=0;
while(rs.next())
{
for(int i=1;i<=cols;i++)
{
obj[c][i]=rs.getString(i);
}
c++;
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
return obj;
}
I am using this code on
button click
updateTable();
jsp = new JScrollPane(jt); // jt is Jtable
jp.add(jsp); //jp is jpanel
please help me out
Not following the naming convention makes it hard to read, but I would suggest to take a closer look at the following piece of code
numberOfColumns = rsMD.getColumnCount();
ColumnNames = new String[numberOfColumns+1];
System.out.println(""+numberOfColumns);
for(int i=1;i<=numberOfColumns;i++)
{
String colName=rsMD.getColumnName(i);
ColumnNames[i] = colName;
System.out.println(""+ColumnNames[i]);
}
Here you explicitly use more column names then numberOfColumns. Idem for your CJ method, where you start at index 1.
Just start all those for loops at index 0, make the arrays one shorter and everything should work
Related
Good day, just wanna ask. I have a Java GUI where I want to add multiple data from SQL server to my Jtable. The flow here is that I would want to use the text field as search field where I will add the info for searching and use the Jbutton to perform the search action then it will give/show me the data to my Jtable. Actually the code is running however some of the data like the 1st data added to my SQL serve and from data id 7 and and up are not showing. How would I fix this and show multiple data with same order ID form SQL server?
Thank you!!
try {
String query = "select * from `sales_product` where order_id = ?";
pst = con.prepareStatement(query);
pst.setString(1, txsearch.getText());
ResultSet rs = pst.executeQuery();
if(rs.next()) {
while(rs.next()) {
String prodname = rs.getString("prodname");
String price = String.valueOf(rs.getInt("price"));
String qty = String.valueOf(rs.getInt("qty"));
String total = String.valueOf(rs.getInt("total"));
model = (DefaultTableModel) datatable.getModel();
model.addRow(new Object[]{
prodname,
price,
qty,
total
});
int sum = 0;
for (int a = 0; a < datatable.getRowCount(); a++) {
sum = sum + Integer.parseInt(datatable.getValueAt(a, 3).toString());
}
Ltotal.setText(Integer.toString(sum));
}
}
else {
JOptionPane.showMessageDialog(this, "No order found!");
txsearch.setText("");
}
} catch (SQLException ex) {
Logger.getLogger(milktea.class.getName()).log(Level.SEVERE, null, ex);
}
}
if(rs.next()) {
while(rs.next()) {
No need for the if (rs.next()) statement. That is causing you to skip the first row of data in the ResultSet.
All you need is the while (rs.next()) statement to create the loop to read all rows in the ResultSet.
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.
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());
my code is this :
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel model=(DefaultTableModel)pl.getModel();
String urlBaseDonnes="jdbc:mysql://localhost:3306/test";
Connection con;
try{
Class.forName("com.mysql.jdbc.Driver");
}catch(ClassNotFoundException ex){
System.out.println(ex);
}
try{
con =DriverManager.getConnection(urlBaseDonnes,"root","");
try (Statement stmt = con.createStatement()) {
ResultSet rs = stmt.executeQuery("SELECT * FROM news");
ResultSetMetaData rsMetaData = rs.getMetaData();
int numberOfColumns = rsMetaData.getColumnCount();
System.out.println("resultSet MetaData column Count=" + numberOfColumns);
int j=0;
pl.setModel(new javax.swing.table.DefaultTableModel(new Object [][] {},new String [] {"ddd","fgg","nl"}));
// get the name of the column, and changing it
for (int i = 1 ; i <= numberOfColumns; i++) {
ChangeName(pl,j,rsMetaData.getColumnName(i));
System.out.println(rsMetaData.getColumnName(i));
System.out.println(j);
j= j+1;
}
String query="SELECT * FROM news";
rs=stmt.executeQuery(query);
//Show the database
while(rs.next()){
String id=rs.getString("id");
String titre=rs.getString("titre");
String contenu=rs.getString("contenu");
model.addRow(new Object[]{id,titre,contenu});
}
rs.close();
}
con.close();
System.out.println("close the database");
}catch(SQLException ex){
System.out.println(ex);
}
}
My goal is to change the name of the columns dynamically when i change the name of my table, this code can change the name of the column but when it's come to showing the content of the database it doesn't work, also i can't add column, for exemple if i choose a table that have 4 column, i'll have an error. I tried to add column using a DefaultTableModel but it didn't work.
could you please help me with the part of adding column dynamically ? and tell me why this code doesn't show what's on the database ?
Thanks
that the data that are in my database are not shown. this code only changes the name of the column.
First you access the TableModel of the table:
DefaultTableModel model=(DefaultTableModel)pl.getModel();
Then you change the TableModel of the table:
pl.setModel(new javax.swing.table.DefaultTableModel(new Object [][] {},new String [] {"ddd","fgg","nl"}));
Then you add the data from the database to the "old" model:
model.addRow(new Object[]{id,titre,contenu});
So the data is NOT added to the current model.
If you want to create a new model then your code should be something like:
DefaultTableModel model = DefaultTableModel(Object[] columnNames, int rowCount);
pl.setModel( model );
Then your code will add the database data to the real model.
The question is why are you trying to hardcode the column name? When you do a select * from the database you don't know how many columns of data will be returned. You should be using more generic code. See the TableFromDatabaseExample.java code from Table From Database.
I'll try to explain as good as I possibly can. I'm a noob and have been trying to fix this for hours now...
I have made a Java application that shows data from a Database that it is connected to. (ODBC/Microsoft SQL).
When I made the GUI for the application I decided to show the data in a jList.
I then realized that the information is too much and that I need column names etc (therefore an jTable)
What I want to do is to CHANGE so that the data shows up in a jTable instead of the jList. But I have no clue how to do it.
This is what the code looks like for now:
GUI
private void jComboBox1_actionPerformed(ActionEvent e)throws SQLException {
String selected = jComboBox1.getSelectedItem().toString();
String[]tmp = conn.showTable1(selected);
jList1.setListData(tmp);
}
Controller
public String[] showTable1(String table)throws SQLException {
ArrayList<String> list1 = dal.showTable1(table);
return list1.toArray(new String[list1.size()]);
}
Data Access Layer
public ArrayList<String> showTable1(String table)throws SQLException {
ArrayList<String> list1 = new ArrayList<String>();
Statement stmt = con.createStatement();
String query1 = "select * from [" +table+"]";
System.out.println(query1);
ResultSet rset = stmt.executeQuery(query1);
ResultSetMetaData rsmd = rset.getMetaData();
while (rset.next()) {
String result = "";
for(int i = 1; i < rsmd.getColumnCount(); i++) {
result += rset.getString(i) + "\t" + "\t";
//
}
list1.add(result);
}
return list1;
}
Please help!
Kind Regards, Chris
See Table From Database for a couple of simple suggestions:
Search the web for an existing ResultSetTableModel.
Use the TableFromDatabase Example code
Use the ListTableModel presented in the blog