How to clear all data inserted in a jTable - java

I designed a jTable that will display data from a table in MySql DB.
The table name is studentrolls with STRollID (int) as primary key and StudentID (Varchar), BachID (year) as foreign keys.
So after typing the StudentID in a jTextField and clicking a jButton only data concerning the student should be displayed in the jTable.
It's working actually but am having two problems, instead of displaying the Year on the year column it's displaying a date for example it should display 2020 but it displaying 2020-01-01.
The main problem is that when I enter another StudentID, it is adding the new results to the old one, so when I enter for the first time a StudentID I get good results and then when I enter another StudentID and click the button I get in the table the new results mixed with the first student's one, etc...
Is there any way to solve this and clear the table before inserting new results?
Here is my code :
private void rSButtonIconDsearchstidActionPerformed(java.awt.event.ActionEvent evt) {
try{
String sqlqueryPastYHi = "SELECT * FROM studentrolls WHERE StudentID = ? ORDER BY BachID";
PreparedStatement preparedStatement = con.prepareStatement(sqlqueryPastYHi);
PreparedStatement pst=con.prepareStatement(sqlqueryPastYHi);
if(!jTextFieldsearchstid.getText().isEmpty() ) {
preparedStatement.setString(1, jTextFieldsearchstid.getText());
ResultSet resultSet = preparedStatement.executeQuery();
while(resultSet.next()){
String scolaryear = resultSet.getString("BachID");
String stclass = resultSet.getString("ClassID");
String totpercent = String.valueOf(resultSet.getInt("PourcentTotal"));
String finalplace = String.valueOf(resultSet.getInt("PlaceFinale"));
String appication = resultSet.getString("Aplication");
String behavior = resultSet.getString("Conduite");
String finalaction = resultSet.getString("ActionFinale");
String pastHistTableData [] = {scolaryear, stclass, totpercent, finalplace, appication, behavior, finalaction};
DefaultTableModel tblModel = (DefaultTableModel)jTablehipastyears.getModel();
tblModel.addRow(pastHistTableData);
}
}
else{
JOptionPane.showMessageDialog(this, "Veillez taper le matricule d'un eleve svp.");
}
}catch (Exception exception){
JOptionPane.showMessageDialog(this, "erreur des donnees: " + exception.getMessage());
}
}

is there any way to solve this and clear the table before inserting new results?
DefaultTableModel tblModel = (DefaultTableModel)jTablehipastyears.getModel();
tblModel.setRowCount(0);
while (...)
{
....
tblModel.addRow(...);
}

thanks #camickr i did changed the code as follow using your methode and it worked.
if(!jTextFieldsearchstid.getText().isEmpty() ) {
preparedStatement.setString(1,
jTextFieldsearchstid.getText());
ResultSet resultSet = preparedStatement.executeQuery();
DefaultTableModel tblModel =
(DefaultTableModel)jTablehipastyears.getModel();
tblModel.setRowCount(0);
while(resultSet.next()){
String scolaryear = resultSet.getString("BachID");
String stclass = resultSet.getString("ClassID");
String totpercent =
String.valueOf(resultSet.getInt("PourcentTotal"));
String finalplace =
String.valueOf(resultSet.getInt("PlaceFinale"));
String appication =
resultSet.getString("Aplication");
String behavior = resultSet.getString("Conduite");
String finalaction =
resultSet.getString("ActionFinale");
String pastHistTableData [] = {scolaryear, stclass,
totpercent, finalplace, appication, behavior,
finalaction};
tblModel.addRow(pastHistTableData);
}

Related

Update records from access database selected row java swing

How To Fix error? I am trying Update the Jtable row data and microsoft access database but it occurred issue.
It Update all rows from the access table instead selected row.
can anyone fix the error? or show me code for it?
**My code is**
DefaultTableModel dtm = (DefaultTableModel) jTable1.getModel();
String id, fname, lname;
connection = ConnectionDb.getConnection();
try{
String value1=txtFname.getText();
String value2=txtLname.getText();
PreparedStatement preparedStatement=connection.prepareStatement("Update Student SET FirstName = '"+value1+"' , LastName ='"+value2+"' where ID = +id");
preparedStatement.execute();
int i = jTable1.getSelectedRow();
if(i >= 0)
{
jTable1.setValueAt(txtFname.getText(), i, 0);
jTable1.setValueAt(txtLname.getText(), i, 1);
}else
{
JOptionPane.showMessageDialog(null, "Error");
}
connection.commit();
}catch(Exception e){
e.printStackTrace();
}
}
There are a few issues in your code:
First: You are not specifying an Id in the Where clause properly. So the update is updating everything.
// Your "Where" means basically "Where 1 = 1"
PreparedStatement preparedStatement=connection.prepareStatement("Update Student SET FirstName = '"+value1+"' , LastName ='"+value2+"' where ID = +id");
Second: It's better to use parameters instead of simply concatenating your variables. Here is how you could do it:
DefaultTableModel dtm = (DefaultTableModel) jTable1.getModel();
String id, fname, lname;
connection = ConnectionDb.getConnection();
try{
String value1=txtFname.getText();
String value2=txtLname.getText();
PreparedStatement preparedStatement = connection.prepareStatement("Update Student SET FirstName = ? , LastName = ? where ID = ?");
preparedStatement.setString(1, value1);
preparedStatement.setString(2, value2);
preparedStatement.setString(3, id);
preparedStatement.execute();
// Code continues..
....
Third: Where is your ID value? You created the variable in the second line but you didn't set any value there. You need to retrieve the value and use it in order to update your Student data.

Deleting selected row in MySQL database through JTable

tb_records = jtable name
records = table name inside my database
Date = my first column
hey = substitute for my real password
mydatabase = name of my database
My problem is that, when I highlight a row in my JTable and delete it, it deletes all the rows. I want to delete the selected row only. Here's my code:
int row = tb_records.getSelectedRow();
DefaultTableModel model= (DefaultTableModel)tb_records.getModel();
String selected = model.getValueAt(row, 0).toString();
if (row >= 0) {
model.removeRow(row);
try {
Connection conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "root", "hey");
PreparedStatement ps = conn.prepareStatement("delete from records where Date='"+selected+"' ");
ps.executeUpdate();
}
catch (Exception w) {
JOptionPane.showMessageDialog(this, "Connection Error!");
}
}
What could be the problem here? How can I delete a selected row in my database and not all the rows?
DefaultTableModel model = (DefaultTableModel) jTable.getModel();
int row = jTable.getSelectedRow();
String eve = jTable.getModel().getValueAt(row, 0).
String delRow = "delete from user where id="+eve;
try {
ps = myCon.getConnection().prepareStatement(delRow);
ps.execute();
JOptionPane.showMessageDialog(null, "Congratulation !!");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
1) Don't display your own message. Display the error message from the Exception as it will give a better explanation what the problem is.
2) Use a proper PreparedStatement for the SQL. You are less likely to make syntax errors. Something like:
String sql = "delete from records where Date= ?";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString( 1, selected );
stmt.executeUpdate();
I don't know much about SQL but maybe you need to pass a Date object not a String object since your where clause is using a Date?
The OP wrote:
SOLUTION: Pick a column with unique values. My Date column has the same values that's why it's deleting all my rows even though I set my row as getSelectedRow. Time_in = my 4th column with unique values.
change
String selected = model.getValueAt(row, 0).toString();
to
String selected = model.getValueAt(row, 3).toString();
and
PreparedStatement ps = conn.prepareStatement("delete from records where Date='"+selected+"' ");
to
PreparedStatement ps = conn.prepareStatement("delete from records where Time_in='"+selected+"' ");

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;

Java PreparedStatement Wilcard doesn't work

I have DDBB with a table users and I'm trying to get fields user_id and user_pass by searching for user_name.
So, when I run the following query:
SELECT `user_id`, `user_pass` FROM `users` WHERE `user_name` LIKE '%aName%';
It returns, ie aName = "John":
+---------+-----------+
| user_id | user_pass |
+---------+-----------+
| 5 | "1234" |
+---------+-----------+
Ok, then I want to perform this using a PreparedStatement, for that reason I have made this function:
private final String QUERY_GETUSERNAME2 =
"SELECT `user_id`, `user_fname`"
+ " FROM `users`"
+ " WHERE `user_fname` LIKE ?;";
private String[][] getUsersInv(String usrName){
ArrayList<String[]> alAux = new ArrayList();
String[][] ret = null;
try{
PreparedStatement st = _conn.prepareStatement(QUERY_GETUSERNAME2);
st.setString(1, "'%"+usrName+"%'");
ResultSet rs = st.executeQuery();
while(rs.next()){
String[] asAux = {String.valueOf(rs.getInt(1)), rs.getString(2)};
alAux.add(asAux);
}//while
}catch(SQLException e){
e.printStackTrace(System.out);
}finally{
if (!alAux.isEmpty()){
ret = new String[alAux.size()][alAux.get(0).length];
for (int i = 0; i < alAux.size(); i++)
ret[i] = alAux.get(i);
}//fi
}
return ret;
}
As you can see, the function returns a String[][], so I check in a previous function if returns is or not null:
public void insertUsersInvTableModel(JTable table, String user){
DefaultTableModel model = (DefaultTableModel) table.getModel();
String[][] row = getUsersInv(user);
if (row != null)
model.addRow(row);
}
And this function is call from the listener for a JButton:
private void addUserActionPerformed(java.awt.event.ActionEvent evt) {
if (comboUsers.getSelectedIndex() != 0){
new Users(_conn).insertUsersInvTableModel(_target, String.valueOf(comboUsers.getSelectedItem()));
_target.validate();
_target.repaint();
setVisible(false);
}
}
As you can imagine, there's a JDialog with a JComboBox with all the users listed down.
As table users is AUTO_INCREMENT, the user_id has some gaps (or maybe it will have), and the only way to build the JComboBox was without relate user_id to JComboBox index.
But, the problem is that whenever I pick an item from the JComboBox, and I run the process to get the user_id and user_pass based on the item selected (nor the index), the ResultSet is always NULL.
Any idea?
Thanks.
replace
st.setString(1, "'%"+usrName+"%'");
with
st.setString(1, "%"+usrName+"%");
The single quotes are automatically added by the PreparedStatement. With the Quotes the query will look for the String '%usrname%' instead of %usrname%
try
st.setString(1, "%"+usrName+"%");
instead of
st.setString(1, "'%"+usrName+"%'");
SOLUTION
As Marco Forberg pointed, quotes used for envolve the string parameter (') are not compulsory. Removing them fix the issue.

Number Format in Jtable

I have a Jtable (tableSummary).
I need to format 2 columns of the table so it's content is in DECIMAL form (e.g. 1,400.00)
How can i do it?
here's my code for the table:
private void tableMarketMouseClicked(java.awt.event.MouseEvent evt) {
String sql = "SELECT tblClientInfo.ClientID, tblrefmarket.MarketDesc, tblclientinfo.LastName, tblledger.LoanAmount, "
+ "tblledger.DateStarted, tblledger.DailyPay, tblledger.Expiry FROM tblclientinfo Inner Join tblbusinessinfo ON tblbusinessinfo.ClientID = tblclientinfo.ClientID "
+ "Inner Join tblrefmarket ON tblbusinessinfo.MarketID = tblrefmarket.MarketID "
+ "Inner Join tblledger ON tblledger.ClientID = tblclientinfo.ClientID where MarketDesc = ?";
try {
//add column to the table model
model.setColumnCount(0); //sets the column to 0 para ig utro click, dili mapun-an ang columns
model.setRowCount(0); //sets the row to 0 para ig utro click, dili mapun-an ang rows
model.addColumn("C NO");
model.addColumn("MARKET");
model.addColumn("BORROWER");
model.addColumn("LOAN");
model.addColumn("START");
model.addColumn("DAILY");
model.addColumn("EXPIRY");
//model.addColumn("BALANCE");
int row = tableMarket.getSelectedRow();
pst = conn.prepareStatement(sql);
pst.setString(1, tableMarket.getModel().getValueAt(row, 0).toString());
rs = pst.executeQuery();
while(rs.next()){
String id = rs.getString(1);
String market = rs.getString(2);
String name = rs.getString(3);
String amt = rs.getString(4);
String start = rs.getString(5);
String daily = rs.getString(6);
String expiry = rs.getString(7);
//String area = rs.getString(3);
model.addRow(new Object[]{ id, market, name, amt, start, daily, expiry});
}
tableSummary.setModel(model);
renderer.setHorizontalAlignment( JLabel.RIGHT );
renderer2.setHorizontalAlignment( JLabel.CENTER );
tableSummary.getColumnModel().getColumn(0).setCellRenderer( renderer2 );
tableSummary.getColumnModel().getColumn(4).setCellRenderer( renderer2 );
tableSummary.getColumnModel().getColumn(6).setCellRenderer( renderer2 );
tableSummary.getColumnModel().getColumn(3).setCellRenderer( renderer );
tableSummary.getColumnModel().getColumn(5).setCellRenderer( renderer );
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, e);
}
}
the columns, amt and daily are the columns i need to be formatted.
Thanks in Advance!
As kleopatra already suggested in her comments
The conversion from Object to a String representation (or any other representation) is the task of the renderer. Your TableModel should just contain the objects
Create and set the appropriate renderer on your JTable (for example by calling JTable#setDefaultRenderer or overriding JTable#getCellRenderer)
As renderer for your Number instances you can use one which uses the NumberFormat for formatting as shown in the answer of Samir
NumberFormat formatter = new DecimalFormat("#,###.00");
String str = formatter.format(1400);
System.out.println(str);

Categories