Fetch result SQL query data to Table JAVA - java

I want to make jtable display my result data from SQL query , the code like this
private void TampilTabel(){
String header[] = {"No","Nama","TTL","Usia"};
DefaultTableModel tabelku = new DefaultTableModel(null, header);
Object obj[] = new Object[10];
jTable1.setModel(tabelku);
TableColumnModel columnModel = jTable1.getColumnModel();
jTable1.setRowHeight(35);
try{
stat = (Statement) koneksiMySQL.GetConnection().createStatement();
String sql = "select No_Induk, Nama, Tgl_Lahir, \n" +
"(YEAR(CURDATE()) - YEAR(Tgl_Lahir)) - (RIGHT(CURDATE(),5) < RIGHT(`Tgl_Lahir`,5))\n" +
"AS Umur\n" +
"FROM tabel_pegawai ORDER BY Nama";
rst = stat.executeQuery(sql);
while (rst.next()){
obj[0] = rst.getString("No_Induk");
obj[1] = rst.getString("Nama");
obj[2] = rst.getString("Tgl_Lahir");
obj[3] = rst.getString("No_Induk");
tabelku.addRow(obj);
}
rst.close();
}catch(SQLException ex){
JOptionPane.showMessageDialog(rootPane, "Data Tidak Ada");
}
}
Question is how to get result data without use getString(), because in my database i didnt have 'Umur' row
Thanks before

Surely you want to do
obj[3] = rst.getString("Umur");
or you could simply do by column number
obj[3] = rst.getString(4);

Related

MySQL results of one table out of two not updating

This is my code and i was trying to update 2 tables.But only one table updates with this code. And no error messages appear as well.
Code:
DefaultTableModel RecordTable = (DefaultTableModel)jTable1.getModel();
int selectedRow = jTable1.getSelectedRow();
String sql ="UPDATE `sales` SET `Username`=?,`Type`=?,`Size`=?,`Unit_Price`=?,`Quantity`=?,`Total`=? WHERE `Type`=?";
String sql2 ="UPDATE `orders` SET `Username`=?,`Total`=? WHERE `Username`=? AND `Total` ";
try {
pst =dbConnection.getConnection().prepareStatement(sql);
String type = jComboBox_type.getSelectedItem().toString();
String size =jComboBox_size.getSelectedItem().toString();
String qty = jSpinner1.getValue().toString();
String tot = String.valueOf(total);
String uprice = String.valueOf(price);
int grstot = Integer.parseInt(jTextField_finaltot.getText())-Integer.parseInt(RecordTable.getValueAt(selectedRow, 4).toString());
finaltotal = grstot +total;
jTextField_finaltot.setText(String.valueOf(finaltotal));
String u = jTextField_usn.getText();
RecordTable.setValueAt(type,jTable1.getSelectedRow(),0);
RecordTable.setValueAt(size,jTable1.getSelectedRow(),1);
RecordTable.setValueAt(uprice,jTable1.getSelectedRow(),2);
RecordTable.setValueAt(qty,jTable1.getSelectedRow(),3);
RecordTable.setValueAt(tot,jTable1.getSelectedRow(),4);
pst.setString(1, u);
pst.setString(2,type );
pst.setString(3,size );
pst.setString(4,uprice);
pst.setString(5,qty );
pst.setString(6,tot);
pst.setString(7, type);
result =pst.executeUpdate();
pst2 =dbConnection.getConnection().prepareStatement(sql2);
pst2.setString(1, u);
pst2.setString(2,tot);
pst2.setString(3,u);
pst2.setString(4,tot);
JOptionPane.showMessageDialog(null,"Record Updated");
} catch (SQLException ex) {
Logger.getLogger(Pizza_Menu.class.getName()).log(Level.SEVERE, null, ex);
}
I was unable to sort out the problem here. please help to find out it!

How to make the table size same as the row size in java?

I have retrieved data from SQL Database into a JTable. I want to make the table size to be automatically the size of the rows. It would be plus if I can also make the data in the rows centered.
I am fairly new to GUI Java Programming. Can someone please let me understand how it can be done?
private void DisplayOrder() {
String qry = "SELECT * FROM SALESORDER"; //Creating Query
try {
conn = DriverManager.getConnection(connectionUrl, username, Pass);
Statement st = conn.prepareStatement(qry);
ResultSet rs = st.executeQuery(qry);
while (rs.next()){
String Des = rs.getString("ProductDescription");
String qty = String.valueOf(rs.getInt("Quantity"));
String price = String.valueOf(rs.getInt("TotalPrice"));
String tbdata[] = {Des, qty, price};
DefaultTableModel model = (DefaultTableModel) Ordertable.getModel();
model.addRow(new Object[]{Des, qty, price});
}
} catch (SQLException e){
} finally{
Ordertable.getTableHeader().setFont(new Font("Segoe UI",Font.BOLD,15));
Ordertable.getTableHeader().setOpaque(false);
Ordertable.getTableHeader().setBackground(new Color(32,136,203));
Ordertable.getTableHeader().setForeground(new Color(255,255,255));
Ordertable.setRowHeight(25);
}
}

display data from the same database colomn into 2 different jtable colomns using self join

I want to display data from the same database colomn into 2 different jtable colomns using that self join from the statement. I'm pretty sure my problem is somewhere here but I don't know how to solve it:
while (rs.next()) {
String d = rs.getString("a.nrzbor");
String e = rs.getString("b.nrzbor");
model.addRow(new Object[]{d, e});
jTable5.setModel(model);
}
Here is the full code:
String de_la = introducereOras1.getText();
String la = introducereOras2.getText();
DefaultTableModel model = new DefaultTableModel(new String[]{"nrzbor1", "nrzbor2"}, 0);
String url = "jdbc:mysql://localhost:3306/aeroport";
String user = "root";
String password = "";
PreparedStatement myStmt = null;
ResultSet rs = null;
try{
Connection myConn = DriverManager.getConnection(url, user, password);
myStmt = myConn.prepareStatement("SELECT a.nrzbor , b.nrzbor" +
"FROM Zboruri a,Zboruri b\n" +
"WHERE (a.de_la = ? AND b.de_la = ?) AND (a.la = ? AND b.la = ?);");
myStmt.setString(1, de_la);
myStmt.setString(2, la);
myStmt.setString(3, la);
myStmt.setString(4, de_la);
rs = myStmt.executeQuery();
while (rs.next()) {
String d = rs.getString("a.nrzbor");
String e = rs.getString("b.nrzbor");
model.addRow(new Object[]{d, e});
jTable5.setModel(model);
}
}
catch(Exception e){
System.err.println("Got an exception!");
System.err.println(e.getMessage());
}
Could anyone help me? Thanks!

JavaFX: Nested Tables

It is possible to create a table that contains other subtables in javafx like in the picture?
The program in the photo is written in javafx only that it is closed source.
Is there any other external or internal component in java that allows me to create a similar interface?
My problem is the same as this: JavaFX TableView: open detail information between rows on click
However, i need to load different value in the sub tables for every row. How can i do this?
This is the creation of my sub-tabs.
private Node createDetailsPane(ObjectProperty<Model> item) {
VBox vBox = new VBox();
ObservableList<Model> dv = FXCollections.observableArrayList();
ObservableList<Model> dl = FXCollections.observableArrayList();
ObservableList<Model> dp = FXCollections.observableArrayList();
TableView visite = new TableView();
TableView latte = new TableView();
TableView parti = new TableView();
visite.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
latte.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
parti.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
visite.setTableMenuButtonVisible(true);
latte.setTableMenuButtonVisible(true);
parti.setTableMenuButtonVisible(true);
visite.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
latte.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
parti.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
visite.getColumns().addAll(idVisita, dataVisita, azioniTerapeutiche, descrizioneVisita, incinta, dataPrevistaParto, veterinario);
latte.getColumns().addAll(idLatte, litri, dataProduzione);
parti.getColumns().addAll(idParto, dataParto, azioniParticolari);
visite.setFixedCellSize(25);
visite.prefHeightProperty().bind(visite.fixedCellSizeProperty().multiply(Bindings.size(visite.getItems()).add(2)));
visite.minHeightProperty().bind(visite.prefHeightProperty());
visite.maxHeightProperty().bind(visite.prefHeightProperty());
latte.setFixedCellSize(25);
latte.prefHeightProperty().bind(latte.fixedCellSizeProperty().multiply(Bindings.size(latte.getItems()).add(2)));
latte.minHeightProperty().bind(latte.prefHeightProperty());
latte.maxHeightProperty().bind(latte.prefHeightProperty());
parti.setFixedCellSize(25);
parti.prefHeightProperty().bind(parti.fixedCellSizeProperty().multiply(Bindings.size(parti.getItems()).add(2)));
parti.minHeightProperty().bind(parti.prefHeightProperty());
parti.maxHeightProperty().bind(parti.prefHeightProperty());
parti.setItems(dp);
latte.setItems(dl);
String id;
if(treeView.getSelectionModel().getSelectedIndices().get(treeView.getSelectionModel().getSelectedItems().size()-1) != -1) {
id = treeView.getSelectionModel().getSelectedItems().get(treeView.getSelectionModel().getSelectedItems().size()-1).getIdProv();
try {
Connection conn = Driver.connection();
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/animali?autoReconnect=true&useSSL=false", "admin", "admincs97");
Statement stmt = conn.createStatement();
sql = "SELECT DISTINCT `ID_VISITA`,`DATA_VISITA`,`AZIONI_TERAPEUTICHE`,`DESCRIZIONE_VISITA`,`STATO_VISITA`,`GRAVIDA_DA_GG`,`DATA_PREVISTA_PARTO`,`VETERINARIO` FROM `visite` "
+ "LEFT JOIN `anagrafe` USING(`ID_PROVVISORIO`, `BOLO`) "
+ "LEFT JOIN `parti` USING(`ID_PROVVISORIO`, `BOLO`) "
+ "LEFT JOIN `latte` USING(`ID_PROVVISORIO`, `BOLO`) "
+where;
String temp = "";
if(where.trim().length() > 0)
temp += " AND visite.`ID_PROVVISORIO` = '"+id+"'";
else
temp = "WHERE visite.`ID_PROVVISORIO` = '"+id+"'";
sql += temp;
ResultSet rs = stmt.executeQuery(sql);
if(rs.next())
do {
dv.add(new Model( rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5), rs.getString(6), rs.getString(7), rs.getString(8)));
/*rs.getString(13), rs.getString(14), rs.getString(15), rs.getString(16), rs.getString(17), rs.getString(18),
rs.getString(19), rs.getString(20), rs.getString(21), rs.getString(22), rs.getString(23), rs.getString(24),
rs.getString(25), rs.getString(26) */
} while(rs.next());
} catch(SQLException e) {
new FxDialogs().showException("Errore", "Errore nel caricamento dei dati", e);
}
}
visite.setItems(dv);
vBox.getChildren().addAll(visite, latte, parti);
return vBox ;
}
Everything works until I select multiple rows in the main table.
If for example I have two main lines, if I select first the second and then the first the subtables give me back the same value.

oracle 11g resultSet how to get the table name

I found there is some problem in Oracle 11g to get table name from interface(ResultSet.getMetaData().getTableName(int column));
It always show the empty string.
Is there something wrong for oracle database or jdbc driver? If the jdbc driver's problem , Can I get another jdbc driver to resolve this issue?
Thanks in advance!
According to the documentation this is not supported:
but does not implement the getSchemaName and getTableName methods because Oracle Database does not make this feasible
Earlier Oracle drivers did have this feature, but it needed to be enabled explicitly because of its performance implications. As far as I can tell from the documentation this is no longer available in more recent drivers.
Please look into the following http://docs.oracle.com/javase/7/docs/api/java/sql/ResultSetMetaData.html
You could use:
DatabaseMetaData metadata = currentConnection.getMetaData();
String[] names = {"TABLE"};
ResultSet tables = metadata.getTables(null,"%", "%", names);
while (tables.next()) {
String tableName = tables.getString("TABLE_NAME");
String tableSchema = tables.getString("TABLE_SCHEM");
}
ResultSet columns = metadata.getColumns(null, "%", tableName, "%");
while (columns.next()) {
String columnName = columns.getString("COLUMN_NAME");
String datatype = columns.getString("TYPE_NAME");
int datasize = columns.getInt("COLUMN_SIZE");
int nullable = columns.getInt("NULLABLE");
}
Read this for more info.
after running into this specifical issue face-first a few days ago, I finally came up with a solution that does the job. Of course it's neither pretty nor... well... anything, but it works.
Basically, I check every table in my database against the columns in the ResultSet.
I hope someone else can use this. Took me about a day to get this straight.
Note: I use a CachedRowSet instead of a ResultSet, which doesn't require me to keep the database connection open the whole time.
private static String getTableNameByCols(ResultSetMetaData rsmd, DatabaseMetaData dbmd) throws SQLException{
String errorString = "No matching table found for the given column Set";
String ret = null, origColName, origDatatype, tableName;
String[] names = {"TABLE"};
ResultSet tables = dbmd.getTables(null, username, "%", names);
// get all the columns out of the rsmd and put them into an Array
Integer numberOfColumns = rsmd.getColumnCount();
String[] origColNames = new String[numberOfColumns+1];
String[] origColTypeNames = new String[numberOfColumns+1];
for (int i=1; i<numberOfColumns+1; i++){
origColNames[i] = rsmd.getColumnName(i);
origColTypeNames[i] = rsmd.getColumnTypeName(i);
}
ResultSet columns = null;
while (tables.next()) {
tableName = tables.getString("TABLE_NAME");
columns = dbmd.getColumns(null, null, tableName, null);
CachedRowSet crs = new CachedRowSetImpl();
crs.populate(columns);
Integer tablesNumberOfColumns = crs.size();
int i = 1;
if (numberOfColumns.intValue() == tablesNumberOfColumns.intValue()){
while (crs.next()) {
origColName = origColNames[i];
origDatatype = origColTypeNames[i];
String colName = crs.getString(4);
String datatype = crs.getString(6);
//int datasize = columns.getInt("COLUMN_SIZE");
//int nullable = columns.getInt("NULLABLE");
if (origColName.equals(colName) && origDatatype.equals(datatype) ){
ret = tableName;
} else {
ret = null;
}
i += 1;
} // looked at all the columns
crs.close();
}// same # of columns check over
if (ret != null) {
break;
}
columns.close();
}
verify(ret, errorString);
return ret;
}
The surrounding method:
private static boolean updateLocalTable(ResultSet rs){
ResultSetMetaData rsmd;
DatabaseMetaData dbmd;
String table_name;
boolean ret = false;
try {
rsmd = rs.getMetaData();
dbmd = conn.getMetaData();
table_name = getTableNameByCols(rsmd, dbmd);
/* ... do stuff with it ... */
} catch (Exception e) {
print("kablooey! \n" + e.getStackTrace());
}
return ret;
}

Categories

Resources