java swing jtable add two table from database in single table [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have table named tbl_income and tbl_expenses...
tbl_income contain four column and four row and tbl_expenses contain four column and three row link in picture below.
I want to mank single table in java swing JTable link picture in below.
how can i make like this.... sorry for bad english..
This is what i've tried:
DefaultTableModel model = (DefaultTableModel) tbldailybook.getModel();
try {
Statement stmt = db.cn.createStatement();
ResultSet rs = stmt.executeQuery("select * from tblincome,tblexpenses");
while (rs.next()) {
model.addRow(new Object[]{rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(6), rs.getString(7), rs.getString(8)});
}
} catch (Exception e) {
}
tblincome have single row but row reply

This is a solution with separate extraction of the two tables and their integration into a common TableModel.
public class MyTableModel extends AbstractTableModel implements TableModel {
private List<Data> inclomeList;
private List<Data> expenseList;
private void setData(List<Data> list, Data data) {
int rows = getRowCount();
int row = list.size();
list.add(data);
if(row < rows) {
fireTableRowsUpdated(row, row);
}
else {
fireTableRowsInserted(row, row);
}
}
public void setIncomeData(Data data) {
if(inclomeList == null) {
inclomeList = new ArrayList<>();
}
setData(inclomeList, data);
}
public void setExpenseData(Data data) {
if(expenseList == null) {
expenseList = new ArrayList<>();
}
setData(expenseList, data);
}
#Override
public String getColumnName(int column) {
switch (column) {
case 0:
case 3:
return "Date";
case 1: return "Income";
case 4: return "Expenses";
case 2:
case 5:
return "Amount";
default:
return super.getColumnName(column);
}
}
#Override
public int getRowCount() {
if(inclomeList == null || expenseList == null) {
if(inclomeList != null) {
return inclomeList.size();
}
else if(expenseList != null) {
return expenseList.size();
}
return 0;
}
return Math.max(inclomeList.size(), expenseList.size());
}
#Override
public int getColumnCount() {
return 6;
}
#Override
public Object getValueAt(int row, int column) {
Data inclome = null;
Data expense = null;
if(inclomeList != null && inclomeList.size() > row) {
inclome = inclomeList.get(row);
}
if(expenseList != null && expenseList.size() > row) {
expense = expenseList.get(row);
}
switch (column) {
case 0: return inclome != null ? inclome.getDate() : "";
case 1: return inclome != null ? inclome.getName() : "";
case 2: return inclome != null ? inclome.getAmount() : "";
case 3: return expense != null ? expense.getDate() : "";
case 4: return expense != null ? expense.getName() : "";
case 5: return expense != null ? expense.getAmount() : "";
}
return null;
}
public void update() {
SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
#Override
protected Void doInBackground() throws Exception {
Database database = new Database();
inclomeList = database.getData(Database.TBL_INCOME);
expenseList = database.getData(Database.TBL_EXPENSES);
return null;
}
#Override
protected void done() {
try {
get();
fireTableDataChanged();
}
catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
};
worker.execute();
}
}
Interface for working with the database:
public class Database {
public static final String TBL_INCOME = "tbl_income";
public static final String TBL_EXPENSES = "tbl_expenses";
private Connection getConnection() throws SQLException {
return DriverManager.getConnection("jdbc:mysql://192.168.40.5/test", "root", "");
}
public List<Data> getData(String tbl_name) throws SQLException {
try (Connection connection = getConnection()) {
String query = "select * from " + tbl_name;
try(ResultSet rs = connection.createStatement().executeQuery(query)) {
List<Data> list = new ArrayList<>();
while (rs.next()) {
Data data = new Data();
data.setDate(rs.getDate("date"));
data.setName(rs.getString("particular"));
data.setAmount(rs.getDouble("amount"));
list.add(data);
}
return list;
}
}
}
}
MainFrame.java
public class MainFrame extends JFrame {
private JTable table = new JTable(new MyTableModel());
public MainFrame() throws HeadlessException {
super("MainFrame");
createGUI();
}
private void createGUI() {
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setPreferredSize(new Dimension(600, 400));
JButton addI = new JButton("+");
addI.addActionListener(e -> ((MyTableModel)table.getModel()).setIncomeData(new Data()));
JButton addE = new JButton("+");
addE.addActionListener(e -> ((MyTableModel)table.getModel()).setExpenseData(new Data()));
JPanel panel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 5, 0));
panel.add(addI);
panel.add(addE);
JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane, BorderLayout.CENTER);
add(panel, BorderLayout.PAGE_END);
pack();
setLocationRelativeTo(null);
((MyTableModel)table.getModel()).update();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new MainFrame().setVisible(true));
}
}

+----+------------+----------------+--------+
| id | dateValue | particular | amount |
+----+------------+----------------+--------+
| 1 | 2017-02-02 | Cash Deposit | 1 |
| 2 | 2017-02-03 | Cheque Deposit | 2 |
| 3 | 2017-02-08 | Cash Deposit | 3 |
| 4 | 2017-02-07 | Product Sales | 4 |
+----+------------+----------------+--------+
+----+------------+------------+--------+
| id | dateValue | particular | amount |
+----+------------+------------+--------+
| 1 | 2017-05-07 | Factory | 6 |
| 2 | 2017-06-02 | Staff | 7 |
| 3 | 2017-06-03 | Travel | 8 |
+----+------------+------------+--------+
I then used select * from income left join expenses on income.id = expenses.id to query the database and got:
+----+------------+----------------+--------+----+------------+------------+--------+--+
| id | dateValue | particular | amount | id | dateValue | particular | amount | |
+----+------------+----------------+--------+----+------------+------------+--------+--+
| 1 | 2017-02-02 | Cash Deposit | 1 | 1 | 2017-05-07 | Factory | 6 | |
| 2 | 2017-02-03 | Cheque Deposit | 2 | 2 | 2017-06-02 | Staff | 7 | |
| 3 | 2017-02-08 | Cash Deposit | 3 | 3 | 2017-06-03 | Travel | 8 | |
| 4 | 2017-02-07 | Product Sales | 4 | | | | | |
+----+------------+----------------+--------+----+------------+------------+--------+--+
Which based on the currently available information is probably the best I can do
You could the use something like Most simple code to populate JTable from ResultSet or Retrieving Data from JDBC Database into Jtable to build the JTable ... as available examples
if second table have more row than table one .. record will not display which are more id in second table – raman dangol 8 hours ago
Also, if there are inconsistent IDs, the records will be lost. That's why I said this was not a trivial question
Then in those cases, something like FULL OUTER JOIN would be more useful. However, based on the information I have, full outer join is not supported in MySQL, because that would be useful. However, based on How to do a FULL OUTER JOIN in MySQL? we could do something like...
select * from income left join expenses on income.id = expenses.id union select * from income right join expenses on income.id = expenses.id where income.id is null
which can generator something like
+----+------------+----------------+--------+----+------------+------------+--------+
| id | datevalue | particular | amount | id | datevalue | particular | amount |
+----+------------+----------------+--------+----+------------+------------+--------+
| 1 | 2017-02-02 | Cash Deposit | 1.0 | 1 | 2017-05-07 | Factory | 6.0 |
| 2 | 2017-02-03 | Cheque Deposit | 2.0 | 2 | 2017-06-02 | Staff | 7.0 |
| 3 | 2017-02-03 | Cash Deposit | 3.0 | 3 | 2017-06-03 | Travel | 8.0 |
| 4 | 2017-02-03 | Product Sales | 4.0 | 4 | 2017-10-01 | Test 1 | 10.0 |
| 5 | 2017-10-02 | Test 2 | 20.0 | | | | |
+----+------------+----------------+--------+----+------------+------------+--------+
Or, if you prefer to keep things aligned to their "selected sides", something like
select income.id, income.datevalue, income.PARTICULAR, income.AMOUNT,
expenses.id, expenses.datevalue, expenses.PARTICULAR, expenses.AMOUNT
from income join expenses on income.id = expenses.id
union all
select income.id, income.datevalue, income.PARTICULAR, income.AMOUNT,
null, null, null, null
from INCOME where not exists (select expenses.id from expenses where expenses.id = income.id)
union all
select null, null, null, null,
expenses.id, expenses.datevalue, expenses.PARTICULAR, expenses.AMOUNT
from expenses where not exists (select income.id from income where income.id = expenses.id)
Which can generate something like...
+----+------------+----------------+--------+----+------------+------------+--------+
| id | datevalue | particular | amount | id | datevalue | particular | amount |
+----+------------+----------------+--------+----+------------+------------+--------+
| 1 | 2017-02-02 | Cash Deposit | 1.0 | 1 | 2017-05-07 | Factory | 6.0 |
| 2 | 2017-02-03 | Cheque Deposit | 2.0 | 2 | 2017-06-02 | Staff | 7.0 |
| 3 | 2017-02-03 | Cash Deposit | 3.0 | 3 | 2017-06-03 | Travel | 8.0 |
| 4 | 2017-02-03 | Product Sales | 4.0 | 4 | 2017-10-01 | Test 1 | 10.0 |
| | | | | 5 | 2017-10-02 | Test 2 | 20.0 |
+----+------------+----------------+--------+----+------------+------------+--------+
At the end of the day, it's still a database issue.
For simplicity, you could create one or more database views in order to simply the query

Related

RowMapper strange result

I am working on a Spring application that use JdbcTemplate to query the database, and the result from the rowmapper is different from the result of the query.
My query returns :
+--------------------+---------+------+------+----------+----------+----------+----------+---------+----------------+-----------------+
| ORIGINATING_SYSTEM | SYS_REF | CUR1 | CUR2 | TRADE_DT | START_DT | END_DT | BOOK_REF | BOOK_ID | NOMINAL | ORIGIN_VALUE_DT |
+--------------------+---------+------+------+----------+----------+----------+----------+---------+----------------+-----------------+
| CC | 4000000 | USD | | 01/04/19 | 01/04/19 | 01/04/19 | TDCZK | 317 | -8245872154,55 | 29/03/19 |
| GPS | 4000000 | EUR | | 01/04/19 | 28/03/19 | 28/03/19 | TDCZK | 317 | 55555550 | |
+--------------------+---------+------+------+----------+----------+----------+----------+---------+----------------+-----------------+
This result is processed with a rowmapper to get a list :
public List<Trade> findBackValueTrades() {
List<Trade> trades = getJdbcTemplate().query(FIND_BACK_VALUE_TRADES, new BackValueTradeMapper());
}
class BackValueTradeMapper implements RowMapper<Trade> {
public BackValueTradeMapper() {
}
#Override
public Trade mapRow(final ResultSet rs, final int rowNum) throws SQLException {
Trade trade = new Trade();
trade.setOriginatingSystem(rs.getString("ORIGINATING_SYSTEM"));
trade.setSystemRef(rs.getString("SYS_REF"));
trade.setNominal(rs.getDouble("NOMINAL"));
Currency cur1 = new Currency();
cur1.setId(rs.getString("CUR1"));
trade.setCurrency1(cur1);
Currency cur2 = new Currency();
cur2.setId(rs.getString("CUR2"));
trade.setCurrency2(cur2);
trade.setTradeDate(rs.getDate("TRADE_DT"));
trade.setStartDate(rs.getDate("START_DT"));
trade.setEndDate(rs.getDate("END_DT"));
Book book = new Book();
book.setBookRef(rs.getString("BOOK_REF"));
book.setId(rs.getLong("BOOK_ID"));
trade.setBook(book);
trade.setNominal(rs.getDouble("NOMINAL"));
trade.setEnteredDate(rs.getDate("ORIGIN_VALUE_DT"));
return trade;
}
}
where Trade is just an #Entity, containing only fields and getters and setters :
#Table(name = "TRADES")
#Entity
public class Trade implements Serializable {
private static final long serialVersionUID = 2143115773381859155L;
#Column(name = "ID")
#Id
private Long id;
#Column(name = "SYS_REF")
private String systemRef;
#Column(name = "ORIGINATING_SYSTEM")
private String originatingSystem;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "CUR1")
private Currency cur1;
// remaining fields + getters/setters
}
The problem is in the resulting list, where it seems the trade from CC was overwritten :
+--------------------+---------+------+------+----------+----------+----------+----------+---------+-----------+-----------------+
| ORIGINATING_SYSTEM | SYS_REF | CUR1 | CUR2 | TRADE_DT | START_DT | END_DT | BOOK_REF | BOOK_ID | NOMINAL | ORIGIN_VALUE_DT |
+--------------------+---------+------+------+----------+----------+----------+----------+---------+-----------+-----------------+
| GPS | 4000000 | EUR | | 01/04/19 | 28/03/19 | 28/03/19 | TDCZK | 317 | 55555550 | 29/03/19 |
| GPS | 4000000 | EUR | | 01/04/19 | 28/03/19 | 28/03/19 | TDCZK | 317 | 55555550 | 28/03/19 |
+--------------------+---------+------+------+----------+----------+----------+----------+---------+-----------+-----------------+
Why is that ?
By the way, I was able to resolve the issue by extending the Trade class and overriding equals and hashCode, but I want to know why it worked.

How can I insert fields into the mysql database but skip a column or two if it's a duplicate?

I'm reading line by line from a file then inserting the details in a mysql database. But the issue is that some lines do not contain a field I called natted ip and port. I loop through the file then insert into db. However the issue is that because not every row contains natted ip and port, I need the database to skip these two columns when inserting into the table where they do not appear but insert the rest and not duplicate. How can I ensure that?
public static void readData() throws ClassNotFoundException, SQLException{
File fileName = new File(FILE);
try(Scanner input = new Scanner(fileName) ){
String firstLine, secondLine, thirdLine;
firstLine = input.nextLine();
secondLine = input.nextLine();
String[] secondString = secondLine.split(" ");
for(String string: secondString){
timestamp = secondString[0]+" "+secondString[1]; //to be inserted
timezone = secondString[2]; //to be inserted
}
thirdLine = input.nextLine();
String[] thirdString = thirdLine.split(":");
for(String string: thirdString){
session = thirdString[1].trim(); //to be inserted
}
while(input.hasNextLine()){
String line;
line = input.nextLine();
String[] cdr_string = line.split(" ");
for(String string:cdr_string){
type = cdr_string[1].trim(); //to be inserted
internalIP_and_port = cdr_string[8];
destinationIP_and_port = cdr_string[10].trim();
}
if(internalIP_and_port.contains("[")){
String[] splitIPs = internalIP_and_port.split(Pattern.quote("["));
for(String string:splitIPs){
internalIP_and_port = splitIPs[0].trim();
nattedIP_and_port = splitIPs[1].trim();
nattedIP_and_port = nattedIP_and_port.substring(0, nattedIP_and_port.length() -1);
}
String[] splitIP_and_port = nattedIP_and_port.split(":");
for(String string:splitIP_and_port){
natted_ip = splitIP_and_port[0].trim(); //to be inserted
natted_port = splitIP_and_port[1].trim(); //to be inserted
}
// System.out.println(natted_ip);
}
String[] split_internal_IP_and_port = internalIP_and_port.split(":");
for(String string : split_internal_IP_and_port){
internal_ip = split_internal_IP_and_port[0].trim(); //to be inserted
internal_port = split_internal_IP_and_port[1].trim(); //to be inserted
}
String[] split_destination_IP_and_port = destinationIP_and_port.split(":");
for(String string : split_destination_IP_and_port){
destination_ip = split_destination_IP_and_port[0].trim(); //to be inserted
destination_port = split_destination_IP_and_port[1].trim(); //to be inserted
}
saveData();
}
}catch(IOException ex){
System.out.println(ex);
}
File log_done = new File(FILE_DONE);
fileName.renameTo(log_done);
fileName.delete();
}
private static void saveData() throws ClassNotFoundException, SQLException{
Connection con = connect();
PreparedStatement stmt = con.prepareStatement("INSERT INTO decoder(type, internal_ip, internal_port, natted_ip, natted_port, destination_ip, destination_port, session, timestamp, timezone, filename) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
stmt.setString(1, type);
stmt.setString(2, internal_ip);
stmt.setString(3, internal_port);
stmt.setString(4, natted_ip);
stmt.setString(5, natted_port);
stmt.setString(6, destination_ip);
stmt.setString(7, destination_port);
stmt.setString(8, session);
stmt.setString(9, timestamp);
stmt.setString(10, timezone);
stmt.setString(11, FILENAME);
stmt.executeUpdate();
}
public static Connection connect() throws ClassNotFoundException, SQLException{
Class.forName("com.mysql.jdbc.Driver");
return DriverManager.getConnection(URL, USERNAME, PASSWORD);
}```
I'm reading from this file:
udp VPN: public --> public 41.72.118.178:56620 --> 103.10.116.19:51130
https VPN: public --> public 10.65.19.224:46765[165.56.53.149:15674] --> 31.13.75.36:443
tcp VPN: public --> public 35.212.240.3:34533 --> 41.72.96.58:20792
dns VPN: public --> public 10.65.179.189:12718 --> 165.56.45.2:53
https VPN: public --> public 10.65.145.37:34490[165.56.53.161:38013] --> 185.60.219.9:443
https VPN: public --> public 10.65.14.63:43956[165.56.53.178:27552] --> 216.58.223.106:443
https VPN: public --> public 10.66.32.44:37573[165.56.53.141:29821] --> 185.60.219.33:443
udp VPN: public --> public 172.21.242.243:10188[41.72.123.88:55777] --> 119.3.74.66:10327
http VPN: public --> public 172.21.218.82:65167[41.72.121.132:46765] --> 5.45.58.214:80
https VPN: public --> public 10.66.118.81:52792[165.56.53.185:46319] --> 104.82.200.59:443
udp VPN: public --> public 76.64.76.78:13114 --> 41.72.108.238:34835
I want it to show like this:
+----+----------+----------------+---------------+---------------+------------
| id | type | internal_ip | internal_port | natted_ip | natted_port
+----+----------+----------------+---------------+---------------+------------
| 1 | udp | 41.72.118.178 | 56620 | NULL | NULL |
| 2 | https | 10.65.19.224 | 46765 | 165.56.53.149 | 15674 |
| 3 | tcp | 35.212.240.3 | 34533 | NULL | NULL |
| 4 | dns | 10.65.179.189 | 12718 | NULL | NULL |
| 5 | https | 10.65.145.37 | 34490 | 165.56.53.161 | 38013 |
| 6 | https | 10.65.14.63 | 43956 | 165.56.53.178 | 27552 |
| 7 | https | 10.66.32.44 | 37573 | 165.56.53.141 | 29821 |
| 8 | udp | 172.21.242.243 | 10188 | 41.72.123.88 | 55777 |
| 9 | http | 172.21.218.82 | 65167 | 41.72.121.132 | 46765 |
| 10 | https | 10.66.118.81 | 52792 | 165.56.53.185 | NULL |
| 11 | udp | 76.64.76.78 | 13114 | NULL | NULL |
| 12 | https | 10.66.81.19 | 34736 | 165.56.53.81 | 29021 |
| 13 | tcp | 10.66.18.62 | 55976 | 165.56.53.233 | 62585
And not like this:
+----+----------+----------------+---------------+---------------+------------
| id | type | internal_ip | internal_port | natted_ip | natted_port
+----+----------+----------------+---------------+---------------+------------
| 1 | udp | 41.72.118.178 | 56620 | NULL | NULL |
| 2 | https | 10.65.19.224 | 46765 | 165.56.53.149 | 15674 |
| 3 | tcp | 35.212.240.3 | 34533 | 165.56.53.149 | 15674 |
| 4 | dns | 10.65.179.189 | 12718 | 165.56.53.149 | 15674 |
| 5 | https | 10.65.145.37 | 34490 | 165.56.53.161 | 38013 |
| 6 | https | 10.65.14.63 | 43956 | 165.56.53.178 | 27552 |
| 7 | https | 10.66.32.44 | 37573 | 165.56.53.141 | 29821 |
| 8 | udp | 172.21.242.243 | 10188 | 41.72.123.88 | 55777
you should initialize natted_ip and natted_port outside of for like below code.
because this variables save data from previous record and you don't clear them. it can be happen for all variables that can be null.
natted_ip = null;
natted_port = null;
for(String string:splitIP_and_port){
natted_ip = splitIP_and_port[0].trim();
natted_port = splitIP_and_port[1].trim();
}

mysql select, insert and delete works from java program, but update not working

I have a table with primary key id, select, insert and delete queries all work from java program, but update query not working, so as to 'insert on duplicate update'( only works when record doesn't exist, when record exists, the updating won't work).
All queries committed, and my mariadb version is 10.1.14.
Thanks in advance for any help!
All queries works well in mysql-cli.
table schema
+------------------+----------------------+------+-----+---------------------+-----------------------------+
| Field | Type | Null | Key | Default | Extra |
+------------------+----------------------+------+-----+---------------------+-----------------------------+
| id | int(10) unsigned | NO | PRI | NULL | |
| posng_valid_type | tinyint(3) unsigned | YES | | NULL | |
| longitude | double(9,6) | NO | | 0.000000 | |
| latitude | double(9,6) | NO | | 0.000000 | |
| heading | smallint(6) | NO | | 0 | |
| altitude | float(7,3) | NO | | 0.000 | |
| gps_speed | smallint(5) unsigned | NO | | 0 | |
| sample_time | timestamp | NO | | 0000-00-00 00:00:00 | |
| update_time | timestamp | NO | | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
+------------------+----------------------+------+-----+---------------------+-----------------------------+
1. update query
update `status_position`
set `status_position`.`id` = 3007,
`status_position`.`posng_valid_type` = 0,
`status_position`.`longitude` = 121.1921,
`status_position`.`latitude` = 31.2797,
`status_position`.`heading` = -1,
`status_position`.`altitude` = 0.0,
`status_position`.`gps_speed` = 0,
`status_position`.`sample_time` = timestamp '2017-02-15 03:52:23.0'
where `status_position`.`id` = 3007;
2. update on duplicate query
insert into `status_position` (
`id`,
`posng_valid_type`,
`longitude`,
`latitude`,
`heading`,
`altitude`,
`gps_speed`,
`sample_time`
) values (
2001,
0,
121.1921,
31.2797,
-1,
0.0,
0,
timestamp '2017-02-15 03:52:23.0'
) on duplicate key update
`status_position`.`id` = 2001,
`status_position`.`posng_valid_type` = 0,
`status_position`.`longitude` = 121.1921,
`status_position`.`latitude` = 31.2797,
`status_position`.`heading` = -1,
`status_position`.`altitude` = 0.0,
`status_position`.`gps_speed` = 0,
`status_position`.`sample_time` = timestamp '2017-02-15 03:52:23.0';
java code with JOOQ which generates the query 2
public <R extends Record> void batchUpsertRecord(Table<R> table, List<R> records) throws PersistenceException {
Connection conn = ConnectionPoolManager.INSTANCE.getConnection();
try (DSLContext dslContext = DSL.using(conn, SQLDialect.MARIADB)) {
List<InsertQuery> insertQueryList = new ArrayList<>();
for (R record : records) {
InsertQuery<R> insert = dslContext.insertQuery(table);
insert.addRecord(record);
insert.onDuplicateKeyUpdate(true);
insert.addValuesForUpdate(mapOfChangedValues(record));
insertQueryList.add(insert);
}
dslContext.batch(insertQueryList).execute();
conn.commit();
} catch (SQLException e) {
logger.error("Failed to upsert record into table({}).", table.getName(), e);
} finally {
ConnectionPoolManager.INSTANCE.closeConnection(conn, logger);
}
}

How to select next record and previous record in SQLite?

I have been searching like forever
I am using min and max for the last and and first record but how do I get the next/ record? I have a column name rowid it is the pk and auto incremented by one every time a user registers
| rowid | Name |
| 1 | John |*
| 2 | Mark |
| 3 | Peter|
| 4 | Help |
so if I click the next button I wanted to select mark which is in rowid 2
| rowid | Name |
| 1 | John |
| 2 | Mark |*
| 3 | Peter|
| 4 | Help |
but if I click the next button twice I want to be in rowid 4
| rowid | Name |
| 1 | John |
| 2 | Mark |
| 3 | Peter|
| 4 | Help |*
how do I do that? by the way I don't have fixed rows since I have a registration function
so here's my code
JButton btnNextLast = new JButton(">>");
btnNextLast.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try{
String sQuery = "select * from accountinfo where rowid = (SELECT MAX(rowid) FROM accountinfo)";
PreparedStatement prst = connection.prepareStatement(sQuery);
ResultSet rs = prst.executeQuery();
lblSID.setText(rs.getString("sid"));
lblfirst.setText(rs.getString("last"));
lblLast.setText(rs.getString("first"));
lblmiddle.setText(rs.getString("middle"));
lblbirth.setText(rs.getString("birth"));
lblcontact.setText(rs.getString("contact"));
}catch(Exception qwe){
}
}
});
I've tried
select rowid
from accountinfo
where rowid >1
order by rowid
limit 1
but no luck
and if I remove order by rowid limit 1. It just show the next record which is 2 and never function again

Removing null elements and keeping non-null elements together on a list in jasper reports

I am using JRBeanCollectionDataSource as datasource for a subreport. Each record in the list contains elements with either null or non-null value . This is my POJO:
public class PayslipDtl {
private String earningSalaryHeadName;
private double earningSalaryHeadAmount;
private String deductionSalaryHeadName;
private double deductionSalaryHeadAmount;
String type;
public PayslipDtl(String salaryHeadName,
double salaryHeadAmount, String type) {
if(type.equalsIgnoreCase("Earning")) {
earningSalaryHeadName = salaryHeadName;
earningSalaryHeadAmount = salaryHeadAmount;
} else {
deductionSalaryHeadName = salaryHeadAmount;
deductionSalaryHeadAmount = salaryHeadAmount;
}
}
//getters and setters
}
Based on the "type", the list is populated as such: {"Basic", 4755, null, 0.0}, {"HRA", 300, null, 0.0}, {null, 0.0, "Employee PF", 925}, {"Medical Allowance", 900, null, 0.0} and so on...
After setting isBlankWhenNull to true and using "Print when" expression, the record is displayed as such:
|Earning |Amount|Deduction |Amount|
--------------------|------|---------------------|------|
| Basic | 4755 | | |
| HRA | 300 | | |
| | | Employee PF | 925 |
| Medical Allowance | 900 | | |
| Fuel Reimbursement| 350 | | |
| | | Loan | 1000 |
---------------------------------------------------------
I want it to be displayed as such:
|Earning |Amount|Deduction |Amount|
--------------------|------|---------------------|------|
| Basic | 4755 | Employee PF | 925 |
| HRA | 300 | Loan | 1000 |
| Medical Allowance | 900 | | |
| Fuel Reimbursement| 350 | | |
---------------------------------------------------------
Setting isRemoveLineWhenBlank to true doesn't work since it is not the entire row which is blank but only a subset of elements of a row that is null.
Is it possible in Jasper?
I am using iReport Designer 5.0.1 with compatibility set to JasperReports3.5.1.
Use a List component for the deduction/amount, here you have a video tutorial on how to do this.
Then deduction and amount fields on the list component need the following options Blank when null and Remove line when blank.
If this still gives you blank lines, try putting both fields on a frame inside the list and mark those options for the frame too.
Only one good solution is, you have to create separate table as:
table employeeED:
srno int,
Earning varchar(50),
EarnAmount Double,
Deduction varchar(50)
DedAmount Double
then you have to insert all earnings in earning side and update all deductions in deductions side.
int i=1;
rs.first();
while(rs.next())
{
if(rs.getString("type").equals("Earning"))
Insert into employeeEd (srno, Earning,EarnAmount) values (i, rs('earning'), rs('eamt'))
}
int j=1;
rs.first();
while(rs.next())
{
if(rs.getString("type").equals("deduction"))
update employeeEd set Deductions='"+rs('earning')+"', DedAmount=" + rs('eamt') + " where srno="+j)
j++;
}
then use employeeED table as datasource.
100% working.

Categories