I'm new to java and DBMS. I'm trying to update/refresh the JTable after any changes made into the H2 database when user clicks a same button to show JTable and after writing data into database(when write button is clicked). I tried some methods and read some posts but couldn't find anything essential to my program. The code below illustrates my problem.
This is the method used to read from database and show it on JTable
public void readActiveData() throws IOException, InstantiationException, IllegalAccessException, SQLException {
try {
st = conn.createStatement();
} catch (SQLException sqlex) {
JOptionPane.showMessageDialog(null, "Can't connect to DB. " + sqlex);
dispose();
}
try {
rs = st.executeQuery("SELECT * FROM main_data WHERE expirationDate > NOW() + 1;");
rs.beforeFirst();
while (rs.next()) {
int id = rs.getInt(1);
String ovogNer = rs.getString(2);
String regNum = rs.getString(3);
String itemName = rs.getString(4);
String note = rs.getString(5);
int zHemjee = rs.getInt(6);
int hvv = rs.getInt(7);
int hugatsaa = rs.getInt(8);
today = rs.getDate(9);
int totalPay = rs.getInt(10);
expirationDate = rs.getDate(11);
rows++;
}
regData = new Object[rows][11];
Object[] Colheads = {"Бүртгэлийн дугаар", "Овог нэр", "Регистрийн дугаар", "Барьцаа",
"Тэмдэглэл", "Зээлийн хэмжээ", "Хүү (%)", "Хугацаа", "Огноо", "Нийт төлөх", "Дуусах хугацаа"};
rs = st.executeQuery("SELECT * FROM main_data WHERE expirationDate > NOW() + 1;");
for (int i1 = 0; i1 < rows; i1++) {
rs.next();
for (int j1 = 0; j1 < 11; j1++) {
regData[i1][j1] = rs.getString(j1 + 1);
}
}
model = new DefaultTableModel(regData, Colheads);
table = new JTable(model);
int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane jsp = new JScrollPane(table, v, h);
activeDataPanel.add(jsp);
rs.close();
st.close();
conn.close();
}
And this is the method i'm using to write data into the database
public void writeDataIntoDB() throws InstantiationException, IllegalAccessException {
ResultSet rs = null;
Connection conn = null;
Statement st = null;
PreparedStatement pst = null;
final String URL = "jdbc:h2:~/registDB";
final String USER = "admin";
final String PASS = "password";
LocalDate currentDate = LocalDate.now();
String input = hugatsaaFld.getText();
long addDays = Long.parseLong(input);
expiration = currentDate.plusDays(addDays);
expirationDate = java.sql.Date.valueOf(expiration);
try {
Class.forName("org.h2.Driver").newInstance();
conn = DriverManager.getConnection(URL, USER, PASS);
String sql = "INSERT INTO main_data(ovogNer,regNum,itemName,note,zHemjee,hvv,hugatsaa,date,totalPay,expirationDate)"
+ "VALUES"
+ "(?,?,?,?,?,?,?,?,?,? )";
pst = conn.prepareStatement(sql);
pst.setString(1, getOvogNer());
pst.setString(2, getRegNum());
pst.setString(3, getItemName());
pst.setString(4, getNote());
pst.setInt(5, +getzHemjee());
pst.setInt(6, +getHvv());
pst.setLong(7, +getHugatsaa());
pst.setDate(8, java.sql.Date.valueOf(LocalDate.now()));
pst.setDouble(9, getTotalPay());
pst.setDate(10, expirationDate);
pst.executeUpdate();
pst.close();
conn.close();
} catch (SQLException se) {
JOptionPane.showMessageDialog(null, "Error: " + se);
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
}
This question has been answered here
but it comes down to clearing and rerendering your JTable object. i.e. refresh, the post above explains it quite nicely.
Hope you get it right.
Related
Form 1 is the textfield located
private void tblOrgMouseClicked(java.awt.event.MouseEvent evt) {
Connection cn = null;
Statement st = null;
ResultSet rss = null;
btnSave.setEnabled(false);
btnUpdate.setEnabled(true);
btnDelete.setEnabled(true);
try {
int row = tblOrg.getSelectedRow();
String cell_click = (tblOrg.getModel().getValueAt(row, 0).toString());
String sql = "SELECT * FROM tbl_organization WHERE org_id = '" + cell_click + "'";
cn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db_organization?zeroDateTimeBehavior=convertToNull", "root", "");
st = cn.prepareStatement(sql);
rss = st.executeQuery(sql);
if (rss.next()) {
String addid = rss.getString("org_id");
txtOrgID.setText(addid);
String addname = rss.getString("org_name");
txtOrgName.setText(addname);
String adddesc = rss.getString("org_description");
txtOrgDesc.setText(adddesc);
String addadviser = rss.getString("org_adviser");
txtAdviserName.setText(addadviser);
}
} catch (Exception e) {
}
}
Form 2 is the Jtable
private void tblAdviserList2MouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
Connection cn = null;
Statement st = null;
ResultSet rss = null;
String ab = " ";
try {
int row = tblAdviserList2.getSelectedRow();
String cell_click = (tblAdviserList2.getModel().getValueAt(row, 0).toString());
String sql = "SELECT * FROM tbl_adviser WHERE adviser_id = '" + cell_click + "'";
cn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db_organization?zeroDateTimeBehavior=convertToNull", "root", "");
st = cn.prepareStatement(sql);
rss = st.executeQuery(sql);
if (rss.next()) {
String addid = rss.getString("firstname").concat(ab).concat(rss.getString("middlename")).concat(ab).concat(rss.getString("lastname"));
new FrmOrganization(addid);
this.setVisible(false);
}
} catch (Exception e) {
}
}
To get the value from a particular cell:
Object cellValue = table.getValueAt(row, col);
Alternatively, you can create a TableModel where each row represents a person object, and add a method on that.
hi my program work in back ground and show different message from database
in specific time the problem always show the same row
//////
**upload code **
public void myMethod(){
long startTime = System.currentTimeMillis();
int counter = 0;
while(true) {
if((System.currentTimeMillis() - startTime ) == 5000){
try{
String host = "jdbc:derby://localhost:1527/Quet";
String uName = "eenas";
String uPass= "2234";
con = DriverManager.getConnection( host, uName, uPass);
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
rs = stmt.executeQuery( "SELECT * from EENAS.EENAS");
rs.next();
int id_col = rs.getInt("ID");
String id =Integer.toString(id_col);
String me=rs.getString("MESSAGE");
System.out.print(me);
rs.close();
}
catch(SQLException err)
{
JOptionPane.showMessageDialog(null, err);
}
startTime = System.currentTimeMillis();
continue; }
else{ continue; } } }
upload code
the can solve this problem by using arrayList to save all data, your program now show only that last one because they change their value every time, the solution like this,
public void DoConnect( ) {
try{
String host = "jdbc:derby://localhost:1527/Quet";
String uName = "eenas";
String uPass= "2234";
con = DriverManager.getConnection( host, uName, uPass);
stmt = con.createStatement();
rs = stmt.executeQuery("select * from EENAS.EENAS");
List<String> PMessage = new ArrayList<String>();
List<Integer> id_col = new ArrayList<Integer>();
while(rs.next()){
id_col.add(rs.getInt("ID"));
PMessage.add(rs.getString("MESSAGE"));
jTextArea1.setText(PMessage);
}
rs.close();
stmt.close();
con.close();
}
catch(SQLException err)
{
JOptionPane.showMessageDialog(null, err);
}
}
I didn't run the code on my machine but this is the logic can solve the problem.
I have a JFrame that has 3 JTextfields and 2 JDatechooser, what I am trying to do is if only one JTextfield has something typed in it and I press the search button, then I will be able to retrieve the data to JTable, but the problem is I have to fill out all JTextFileds and JDatechooser in order to retrieve data. My idea is to ignore null JTextfields and JTdatechooser if only one JTextfield has the keyword I want ?? Any suggestions ?? Thanks in advance,
public ArrayList<BillsRecord> getBillRecordByID(int EmpCode, String Fname, String Lname, String sDate, String eDate) throws SQLException {
String sql = "SELECT B.DATE AS DT, B.EMP_ID, E.FNAME, E.LNAME, MONEY_SENT, RENT, PHONE, GAS, ELECTRICITY, INTERNET, OTHER"
+ " FROM EMPLOYEE E INNER JOIN BILLS B ON E.EMP_ID = B.EMP_ID"
+ " WHERE B.EMP_ID = ? "
+ " OR E.FNAME = ? "
+ " OR E.LNAME = ? "
+ " OR DATE BETWEEN ? AND ? "
+ " ORDER BY B.DATE";
DBConnection con = new DBConnection();
Connection connect = con.getConnection();
PreparedStatement ps = null;
ArrayList<BillsRecord> records = new ArrayList<>();
try {
ps = connect.prepareStatement(sql);
ps.setInt(1, EmpCode);
ps.setString(2, Fname);
ps.setString(3, Lname);
ps.setString(4, sDate);
ps.setString(5, eDate);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
BillsRecord billrec = new BillsRecord();
billrec.setDATE(rs.getString("DT"));
billrec.setEMP_ID(rs.getInt("EMP_ID"));
billrec.setFNAME(rs.getString("FNAME"));
billrec.setLNAME(rs.getString("LNAME"));
billrec.setMONEY_SENT(rs.getDouble("MONEY_SENT"));
billrec.setRENT(rs.getDouble("RENT"));
billrec.setPHONE(rs.getDouble("PHONE"));
billrec.setGAS(rs.getDouble("GAS"));
billrec.setELECTRICITY(rs.getDouble("ELECTRICITY"));
billrec.setINTERNET(rs.getDouble("INTERNET"));
billrec.setOTHER(rs.getDouble("OTHER"));
records.add(billrec);
return records;
}
} catch (SQLException e) {
System.out.println(e.toString());
} finally {
if (ps != null) {
ps.close();
}
if (connect != null) {
connect.close();
}
}
return null;
}
private void search() {
try {
JTextField stxt = ((JTextField) startdatetxt.getDateEditor().getUiComponent());
String sDATE = stxt.getText().trim();
JTextField etxt = ((JTextField) enddatetxt.getDateEditor().getUiComponent());
String eDATE = etxt.getText().trim();
int EMP_ID = Integer.parseInt(this.empidtxt.getText().trim());
String FNAME = this.firstnametxt.getText().trim();
String LNAME = this.lastnametxt.getText().trim();
BillRecordDao billrecdao = new BillRecordDao();
ArrayList<BillsRecord> records = billrecdao.getBillRecordByID(EMP_ID, FNAME, LNAME, sDATE, eDATE);
Object[] tableColumnName = new Object[11];
tableColumnName[0] = "Date";
tableColumnName[1] = "H.License";
tableColumnName[2] = "First Name";
tableColumnName[3] = "Last Name";
tableColumnName[4] = "MONEY SENT";
tableColumnName[5] = "RENT";
tableColumnName[6] = "PHONE";
tableColumnName[7] = "GASE";
tableColumnName[8] = "ELECTRICITY";
tableColumnName[9] = "INTERNET";
tableColumnName[10] = "OTHER";
DefaultTableModel tbd = new DefaultTableModel();
tbd.setColumnIdentifiers(tableColumnName);
this.BillsSummaryTable.setModel(tbd);
Object[] RowRec = new Object[11];
for (int i = 0; i < records.size(); i++) {
RowRec[0] = records.get(i).getDATE();
RowRec[1] = records.get(i).getEMP_ID();
RowRec[2] = records.get(i).getFNAME().toUpperCase();
RowRec[3] = records.get(i).getLNAME().toUpperCase();
RowRec[4] = records.get(i).getMONEY_SENT();
RowRec[5] = records.get(i).getRENT();
RowRec[6] = records.get(i).getPHONE();
RowRec[7] = records.get(i).getGAS();
RowRec[8] = records.get(i).getELECTRICITY();
RowRec[9] = records.get(i).getINTERNET();
RowRec[10] = records.get(i).getOTHER();
tbd.addRow(RowRec);
}
} catch (SQLException e) {
System.out.println(e.toString());
}
}
Basically, you need to create a variable/dynamic query based on the available values
Now, you can do this using something like StringBuilder or even storing each query element in a List or array, but you always end up with the "trailing OR" problem (you need to know when you've got to the last element and not append the "OR" to the String or remove the trailing "OR" from the resulting String). While not difficult, it's just a pain.
However, if you're using Java 8, you can use StringJoiner!
StringJoiner sj = new StringJoiner(" OR ");
String sql = "SELECT B.DATE AS DT, B.EMP_ID, E.FNAME, E.LNAME, MONEY_SENT, RENT, PHONE, GAS, ELECTRICITY, INTERNET, OTHER"
+ " FROM EMPLOYEE E INNER JOIN BILLS B ON E.EMP_ID = B.EMP_ID"
+ " WHERE ";
List values = new ArrayList();
// EmpCode MUST be a Integer, so it can be null
if (EmpCode != null) {
sj.add("B.EMP_ID = ?");
values.add(EmpCode);
}
if (FName != null) {
sj.add("E.FNAME = ?");
values.add(FName);
}
if (LName != null) {
sj.add("E.LNAME = ?");
values.add(LName);
}
if (sDate != null && eDate != null) {
sj.add("DATE BETWEEN ? AND ?");
values.add(sDate);
values.add(eDate);
}
sql += sj.toString();
Connection connect = null;
try (PreparedStatement ps = connect.prepareStatement(sql)) {
for (int index = 0; index < values.size(); index++) {
ps.setObject(index + 1, values.get(index));
}
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
//...
}
}
} catch (SQLException exp) {
exp.printStackTrace();
}
You might also like to have a look at The try-with-resources Statement and have a read through Code Conventions for the Java TM Programming Language, it will make it easier for people to read your code and for you to read others
actually I have 10-30 dummies to get the value from txtCC, but i'd only used 3 dummies for example below..
So how do I get each values and save it directly to my database without using dummy? It's a big deal coz' my code was too large to compile using those dummies..
THANKS for any help..
private void bSaveActionPerformed(java.awt.event.ActionEvent evt)
{
// Save to database
String cc = txtCC.getText();
String delimiter = ",";
String[] temp;
temp = cc.split(delimiter);
for(int i = 0; i < temp.length; i++)
if(i==0) {
txtC1.setText(temp[0]);
txtC2.setText("0");
txtC3.setText("0"); }
else if (i==1) {
txtC1.setText(temp[0]);
txtC2.setText(temp[1]);
txtC3.setText("0"); }
else if (i==2) {
txtC1.setText(temp[0]);
txtC2.setText(temp[1]);
txtC3.setText(temp[2]); }
try {
String cc1 = txtC1.getText(); int CC1 = Integer.parseInt(cc1);
String cc2 = txtC2.getText(); int CC2 = Integer.parseInt(cc2);
String cc3 = txtC3.getText(); int CC3 = Integer.parseInt(cc3);
int opt = JOptionPane.showConfirmDialog(null,"Are you sure you want to save this record? ");
if (opt == 0){
if(!txtC1.getText().equals("0")) {
stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
String sql = "Select * from tbl_liqinfo";
rs = stmt.executeQuery(sql);
rs.next();
rs.moveToInsertRow();
rs.updateInt("CC", CC1);
rs.insertRow();
rs.close();
}
if(!txtC2.getText().equals("0")) {
stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
String sql = "Select * from tbl_liqinfo";
rs = stmt.executeQuery(sql);
rs.next();
rs.moveToInsertRow();
rs.updateInt("CC", CC2);
rs.insertRow();
rs.close();
}
if(!txtC3.getText().equals("0")) {
stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
String sql = "Select * from tbl_liqinfo";
rs = stmt.executeQuery(sql);
rs.next();
rs.moveToInsertRow();
rs.updateInt("CC", CC3);
rs.insertRow();
rs.close();
}
}
}
catch (SQLException err){
JOptionPane.showMessageDialog(FrmEmpLiquidation.this, err.getMessage());
}
}
Instead of using dummies, create simple small methods and make use of it. This will reduce you line of code. and also easy to understand.
private void bSaveActionPerformed(java.awt.event.ActionEvent evt){
// Save to database
String cc = txtCC.getText();
String delimiter = ",";
String[] temp;
temp = cc.split(delimiter);
for(int i = 0; i < temp.length; i++)
insertData(temp[i]);
}
public void insertData(final String data){
txtC1.setText(data);
try {
String cc1 = txtC1.getText(); int CC1 = Integer.parseInt(cc1);
int opt = JOptionPane.showConfirmDialog(null,"Are you sure you want to save this record? ");
if (opt == 0){
if(!txtC1.getText().equals("0")) {
stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
String sql = "Select * from tbl_liqinfo";
rs = stmt.executeQuery(sql);
rs.next();
rs.moveToInsertRow();
rs.updateInt("CC", CC1);
rs.insertRow();
rs.close();
}
}
}
catch (SQLException err){
JOptionPane.showMessageDialog(FrmEmpLiquidation.this, err.getMessage());
}
}
I'm trying to get the data from database but get nothing. The problem is
ResultSet resultSet = statement.executeQuery(readQuery);
always empty. And
while (resultSet.next())
is never executing.
Would really appreciate any help
public class DB {
public Connection connect() {
Connection connection = null;
try {
String databaseURL = "jdbc:derby://localhost:1527/DB;create=true;user=user;password=password";
Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
connection = DriverManager.getConnection(databaseURL);
}
catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException ex) {
Logger.getLogger(DB.class.getName()).log(Level.SEVERE, null, ex);
}
return connection;
}
ArrayList read(Connection connection, String table, String column, String value) {
ArrayList results = new ArrayList();
Statement statement = null;
try {
statement = connection.createStatement();
String readQuery = "select * from " + table + " where " + column + " = '" + value + "'";
out.print(readQuery);
ResultSet resultSet = statement.executeQuery(readQuery);
while (resultSet.next()) {
ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
int numberOfColumns = resultSetMetaData.getColumnCount();
out.print("Read\n");
for (int i = 1; i < numberOfColumns + 1; i++) {
results.add(resultSet.getString(i));
}
}
statement.close();
connection.close();
}
catch (SQLException ex) {
}
return results;
}
}