How to get selected rows from a database into a jTable? - java

I have a database table which has many patient details like registration id, registration date etc. I want to perform a date based search of the patients and get the result into a jTable. ( for example, if I type 23-05-2013 as the registration date, all the patients admitted on 23 May should be displayed in a jTable. How do I do that?
This is the code I have used:
public void getTableData() {
try {
con = getConnection.getCon();
String sql = "SELECT * FROM patientrecords WHERE Registration Date = ?";
pst.setString(1, regdate.getText());
pst = con.prepareStatement(sql);
rs = pst.executeQuery();
if (rs.next()) {
patient_table.setModel(DbUtils.resultSetToTableModel(rs));
}
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, e);
}
}

1) You should make your own TableModel implementation or extending AbstractTableModel
2) Map patientrecords to object world. Also entity name should be in singular. So you will have a java-bean like PatientRecord.
3) You'll have a List<PatientRecord> data as DataHolder.
Fill like
while (rs.next()) {
data.add(new PatientRecord(..));
}
4) In some part you should set in your jtable.setModel(..)
This previous question may help you simple code to populate jtable from resultset

Related

How can I properly write a SQL query to update record data in a JTable?

To better imagine the situation, I have a Jtable - which saves some records. When I want to edit a record - I have a button for this - I click on it, edit the cell. but the data is not saved, after refreshing the program, do not see the edited record, only the previous record.
query: update employe set name = ?,salary = ?,number = ? where id = ?
I suppose there is something wrong with the query ( not too specific?).
The previous version of the program did not allow to point to a given record with the mouse, but I entered a given record for editing in the text field and the query worked - there I pointed to a specific id for editing, now it points only to a given cell.
And I am wondering what is the problem, after all, the cell is edited but not saved?
updateButton.addActionListener(e -> {
String id, name, salary, mobile;
name = txtName.getText();
salary = txtSalary.getText();
mobile = txtNumber.getText();
id = txtID.getText();
try {
updateSelectedRows(table);// allows to edit cells with the mouse
pst = con.prepareStatement("update employe set name = ?,salary = ?,number = ? where id = ?");
pst.setString(1, name);
pst.setString(2, salary);
pst.setString(3, mobile);
pst.setString(4, id);
pst.executeUpdate();
tab_show();//refresh table, SELECT database query
txtName.setText("");
txtSalary.setText("");
txtNumber.setText("");
txtName.requestFocus();
} catch (SQLException e1) {
e1.printStackTrace();
}
function updateSelectedRows:
public void updateSelectedRows(JTable table) {
DefaultTableModel model = (DefaultTableModel) table1.getModel();
int i = table.getSelectedRow();
model.setValueAt(txtName.getText(), i, 1);
model.setValueAt(txtSalary.getText(), i, 2);
model.setValueAt(txtNumber.getSelectedItem(), i, 3);
}

Getting all data between 2 days in MySql Java

I want to select all data from database table between given 2 specific dates and add that data to a jtable.
Below is my code to retrieve data from the database; But all the data is not shown by this code .. What is the error I done here?
private void updateTable(){
String fday = ((JTextField)day_chooser.getDateEditor().getUiComponent()).getText();
String tday = ((JTextField)day_chooser.getDateEditor().getUiComponent()).getText();
try {
String sql = "SELECT * FROM saleinfo WHERE SaleDate BETWEEN '"+fday+"' AND '"+tday+"'";
pst=conn.prepareStatement(sql);
rs=pst.executeQuery();
tbl.setModel(DbUtils.resultSetToTableModel(rs));
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Error : "+ex);
}
}
Leverage the JDBC drive and it's ability to map between data types from Java to the database, leverage the power of the PreparedStatement
I'm using prepared statements pst is the prepare statement
BUT, you're not using it properly, see Using Prepared Statements for more details.
Start by getting the Date value from the date picker (I'm guessing here, but I assume they have some kind of getDate method) and then bind the values to the wildcard columns of the query, for example...
Date fday = day_chooser.getDate();
Date tday = day_chooser.getDate();
try {
String sql = "SELECT * FROM saleinfo WHERE SaleDate BETWEEN ? AND ?";
try (PreparedStatement pst = conn.prepareStatement(sql)) {
pst.setDate(1, new java.sql.Date(fday.getTime()));
pst.setDate(2, new java.sql.Date(tday.getTime()));
try (ResultSet rs = pst.executeQuery()) {
tbl.setModel(DbUtils.resultSetToTableModel(rs));
}
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Error : " + ex);
ex.printStackTrace();
}
Don't assume anything about the format, this will just cause you no end of grieve if you ever have to change databases

Updating JTable when selecting item in combobox in Java

I coded auto suggesting comboBox that retrieve data from SQL database.It was successful.
Then as next step, I want these functionalities to be done,
*When user select a "ItemID" from the comboBox(When the user type first letter of ItemID, suggest list comes and user can select aItemID - successfully coded), JTable's "ItemID" column and other columns that related to that specific "ItemID" must be updated from the database.
I coded updateTable()method as below;
private void updateTable(){
String existID = (String) IDcombo.getSelectedItem();
String sql = "select * from druginfo WHERE ItemId LIKE '"+existID+"%'";
try {
PreparedStatement pst = conn.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
saleTable.setModel(DbUtils.resultSetToTableModel(rs));
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex);
} }
Well your tablemodel needs to fire according to the event. If only table data changes then it should fire fireTableDataChanged(). If data and structure both changes then it should fire fireTableStructureChanged(). You can refer to the document
If you're still having trouble with this the one way is to call repaint on your table but that's not a very good way of doing things.

Set Cell value in jtable based on entry made in another cell using keyreleased event

I have a jtable that is linked to a mysql table.
The table has two columns 'Item_no' and 'Item_description'
What I want is: Once a user completes typing the item_no in the jtable, the adjacent cell(Item Description) is filled with the corresponding description from the database.
Override setValueAt of the TableModel. When the item number column value is set, load the corresponding value from the database and update the model accordingly.
See How to use tables for more details
Solved!!!
AllocationsTable.getCellEditor(0,0).addCellEditorListener(new CellEditorListener() {
#Override
public void editingStopped(ChangeEvent ce) {
PreparedStatement ps;
String sql = "Select * from items where item_no= ?";
try
{
for (i=0;i<model.getRowCount();i++)
{
ps = conn.prepareStatement(sql);
ps.setString(1,model.getValueAt(i, 0).toString());
ResultSet rst;
rst = ps.executeQuery();
rst.last();
model.setValueAt(rst.getString("Description"), i, 1);
model.fireTableCellUpdated(i, 1);
}
}
catch(SQLException ex)
{
JOptionPane.showMessageDialog(null,ex.getMessage());
}

load data from selected table row in java

I'm trying to user mouse event to display the selected row from jtable in other text field but when i run it and clicked on any row it's coming with this message java.sql.Exception [microsoft ][odbc microsoft access drive] data type mismatch in criteria exception
please any idea can help
this is the code :
private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {
try
{
int row = jTable1.getSelectedRow();
String Table_Click = (jTable1.getModel().getValueAt(row,0).toString());
String Sql= "SELECT * FROM tblUsers WHERE ID='" + Table_Click +"' ";
pst = con.prepareStatement(Sql);
rs = pst.executeQuery();
if(rs.next())
{
String Add1= rs.getString("ID");
jTextField_ID.setText(Add1);
String AddBrNa= rs.getString("UserName");
jTextField_UN.setText(AddBrNa);
String AddBrAdd= rs.getString("Password");
jPasswordField_Pass.setText(AddBrAdd);
String AddBrYear= rs.getString("FName");
jTextField_FN.setText(AddBrYear);
String AddBrCourse= rs.getString("LName");
jTextField_LN.setText(AddBrCourse);
String AddBrSec= rs.getString("DateCreated");
jTextField_date.setText(AddBrSec);
JOptionPane.showMessageDialog(null, "errorif");
}
else
{
JOptionPane.showMessageDialog(null, "error");
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
}
I'm trying to user mouse event to display the selected row from jtable
in other text field
There's no need to use MouseListener to do that. Just implement a ListSelectionListener instead, that will be executed even if the selection change is made through keyboard or code:
jTable1.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
// Your code here
}
};
If you still want to use MouseListener then I'd suggest you make this change:
//int row = jTable1.getSelectedRow();
int row = jTable1.rowAtPoint(evt.getPoint());
Because you can't be sure the row selection will change before this event is triggered. I'm not sure but I would say a MouseEvent should have precedence over a ListSelectionEvent.
However be aware thisrow index belongs to the view, not the model, so the following line may not return the expected result if your table is a sorted one:
String Table_Click = (jTable1.getModel().getValueAt(row,0).toString());
It should be:
String Table_Click = (jTable1.getValueAt(row,0).toString());
Having said this, the proper use of PreparedStatemen is the one #camickr just pointed out:
String sql = "SELECT * FROM tblUsers WHERE ID = ?";
PreparedStatement pst = con.prepareStatement(sql); //
pst.setString(1, Table_Click) // assuming the ID is a varchar, since you enclosed it into ''
Also be aware that you're accessing your database in the Event Dispatch Thread. You should do that in a separate thread and update Swing components in the EDT. SwingWorker sounds like a good match in this case.
java.sql.Exception [microsoft ][odbc microsoft access drive] data type mismatch in criteria exception: is nothing to do with your table. Check your SQL query. Most likely your ID is an integer type but you are checking it as string, inside your where clause:
WHERE ID='" + Table_Click +"'
Try using a PreparedStatement to make the SQL easier. If you do need to use an int as suggested by Sage then you can do:
String sql = "SELECT * FROM tblUsers WHERE ID = ?";
PreparedStatement pst = con.prepareStatement(sql);
pst.setInt(1, ...)
thanks all,
this is working fine:
String Sql= "SELECT * FROM tblUsers WHERE ID=" + Table_Click;

Categories