how to sort a table from database - java

I want to be able to sort a table from the database, according to either the quatity or the name, but how do i decided what happens in what case?
Below is the code for the table.
public void tableupdate(JTable jTable1, String fill) {
try {
try {
Class.forName("org.h2.Driver");
Connection con = DriverManager.getConnection("jdbc:h2:file:D:/Inventory.db", "sa", "");
Statement stat = con.createStatement();
fill = "SELECT * FROM BOOKDESC ";
ResultSet rs = stat.executeQuery(fill);
while (jTable1.getRowCount() > 0) {
((DefaultTableModel) jTable1.getModel()).removeRow(0);
}
int columns = rs.getMetaData().getColumnCount();
while (rs.next()) {
Object[] row = new Object[columns];
for (int i = 1; i <= columns; i++) {
row[i - 1] = rs.getObject(i);
}
((DefaultTableModel) jTable1.getModel()).insertRow(rs.getRow() - 1, row);
}
rs.close();
stat.close();
con.close();
} catch (ClassNotFoundException e) {
JOptionPane.showMessageDialog(null, e);
}
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, e);
}
}

MySQL is offering a method for sorting data in your SELECT statement, it's called ORDER BY.
Usage is found here.
This way, your code doesn't have to do the work, as your ResultSet already gets sorted data.

Related

It won't display the filtered range of date in the table

I want to get the data from the two dates in MySQL and display only the range, however even if it is blank it won't display anything. Moreover, even if I change the simple date format to MM/dd/yyyy the table only display one row and date even I have 2 rows in the database daated 07/14/2022
Here is my code
private void table_stocks(String date_from, String date_to) {
try {
int table;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection(url, username, password);
if(date_from.equals("") || date_to.equals("")){
pst = con.prepareStatement("SELECT `sales_number`, `date`, `amount_due` FROM `dnk_database`.`sales`;");
}
else{
pst = con.prepareStatement("SELECT `sales_number`, `date`, `amount_due`, SUM(`amount_due`) AS `total_sales` FROM `dnk_database`.`sales` WHERE `date` BETWEEN ? AND ?;");
pst.setString(1, date_from);
pst.setString(2, date_to);
}
ResultSet rs = pst.executeQuery();
ResultSetMetaData rsd = rs.getMetaData();
table = rsd.getColumnCount();
DefaultTableModel load = (DefaultTableModel)jTable_salesValue.getModel();
load.setRowCount(0);
while(rs.next()) {
Vector v2 = new Vector();
for(int i = 1; i <= table; i++){
v2.add(rs.getString("sales_number"));
v2.add(rs.getString("date"));
v2.add(rs.getString("amount_due"));
}
load.addRow(v2);
}
} catch (ClassNotFoundException ex) {
Logger.getLogger(Add_Items.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (SQLException ex) {
Logger.getLogger(Add_Items.class.getName()).log(Level.SEVERE, null, ex);
}
}
Also, want to display the SUM of the amount_due column from my SQL to a textfield and I don't know where to place this code
if (rs.next()==true) {
String sum_total = rs.getString("total_sales");
jTextField_totalSales.setText(sum_total);
}
You can accumulate the sum to a variable before the while loop, I assume you are using integer data type, then inside the loop sum the value. After the while loop is done display in the text field
int sumTotal = 0;
while(rs.next()) {
Vector v2 = new Vector();
for(int i = 1; i <= table; i++){
v2.add(rs.getString("sales_number"));
v2.add(rs.getString("date"));
v2.add(rs.getString("amount_due"));
sumTotal += rs.getString("amount_due") == null? 0 : Integer.parseInt(rs.getString("amount_due"));
}
load.addRow(v2);
jTextField_totalSales.setText(sumTotal);
}

importing last row of mysql database in all rows of jtable (Java Swing)

I'm trying to import all of the data from mysql database into a jtable using arraylists but something isn't working right, as i get the number of rows right but they're all values of the last row
Here's the code
public ArrayList<medicaments> medicaments_list() {
ArrayList<medicaments> medicament_lists = new ArrayList<medicaments>();
String select_nom_type_med = "select * from medicaments where login=?";
PreparedStatement stmt;
ResultSet rs2;
medicaments med;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "");
stmt = con.prepareStatement(select_nom_type_med);
stmt.setString(1, Utilisateur.getLogin());
rs2 = stmt.executeQuery();
while (rs2.next()) {
emptytable = false;
med = new medicaments(rs2.getInt("med_id"), rs2.getString("login"), rs2.getString("med_nom"), rs2.getString("med_type"), rs2.getString("date_debut"), rs2.getString("date_fin"), rs2.getString("frequence"), rs2.getString("temps_1"), rs2.getString("temps_2"), rs2.getString("temps_3"), rs2.getString("temps_4"), rs2.getString("temps_5"), rs2.getString("Stock"), rs2.getString("rappel_stock"));
medicament_lists.add(med);
}
} catch (ClassNotFoundException e1) {
System.out.println(e1);
} catch (SQLException e1) {
System.out.println(e1);
}
return medicament_lists;
}
public void populate_jTable_from_db() {
ArrayList<medicaments> dataarray = medicaments_list();
model = (DefaultTableModel) jTable1.getModel();
model.setRowCount(dataarray.size());
int row = 0;
for (medicaments data : dataarray) {
model.setValueAt(data.get_nom_med(), row, 0);
model.setValueAt(data.get_type_med(), row, 1);
row++;
}
jTable1.setModel(model);
}
and here's the result :(there's 3 rows in my database and po is the last one i added)
Make sure your recordset actually contains something and it's what you really want:
while (rs2.next()) {
if (rs2.getString("login").equals(Utilisateur.getLogin())) {
emptytable = false;
med = new medicaments(rs2.getInt("med_id"), rs2.getString("login"),
rs2.getString("med_nom"), rs2.getString("med_type"),
rs2.getString("date_debut"), rs2.getString("date_fin"),
rs2.getString("frequence"), rs2.getString("temps_1"),
rs2.getString("temps_2"), rs2.getString("temps_3"),
rs2.getString("temps_4"), rs2.getString("temps_5"),
rs2.getString("Stock"), rs2.getString("rappel_stock"));
medicament_lists.add(med);
}
}

APOSTROPHE issue with java and SQL

I have code, where I have single quote or APOSTROPHE in my search
I have database which is having test table and in name column of value is "my'test"
When running
SELECT * from test WHERE name = 'my''test';
this works fine
If I use the same in a Java program I am not getting any error or any result
But If I give the name with only single quote then it works
SELECT * from test WHERE name = 'my'test';
Could you please help me out to understand.
Java code is
Connection con = null;
PreparedStatement prSt = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.
getConnection("jdbc:oracle:thin:#localhost:1521:orcl"
,"user","pwd");
String query = "SELECT * from "
+ "WHERE name = ? ";
prSt = con.prepareStatement(query);
String value = "my'mobile";
char content[] = new char[value.length()];
value.getChars(0, value.length(), content, 0);
StringBuffer result = new StringBuffer(content.length + 50);
for (int i = 0; i < content.length; i++) {
if (content[i] == '\'')
{
result.append("\'");
result.append("\'");
}
else
{
result.append(content[i]);
}
}
prSt.setObject(1, result.toString());
int count = prSt.executeUpdate();
System.out.println("===============> "+count);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally{
try{
if(prSt != null) prSt.close();
if(con != null) con.close();
} catch(Exception ex){}
}
You don't have to escape anything for the parameter of a PreparedStatement
Just use:
prSt = con.prepareStatement(query);
prSt.setString("my'mobile");
Additionally: if you are using a SELECT statement to retrieve data, you need to use executeQuery() not executeUpdate()
ResultSet rs = prst.executeQuery();
while (rs.next())
{
// process the result here
}
You might want to go through the JDBC tutorial before you continue with your project: http://docs.oracle.com/javase/tutorial/jdbc/index.html

Java - NULL ResultSet

I have a function to fetch data from MySQL table
public ResultSet getAddressID(String city) throws SQLException{
String q = "SELECT PK_ADDRESS_ID FROM tbl_addresses WHERE city =" + "\""+ city+ "\";";
ResultSet rs = executeSearch(q);
return rs;
}
When I try System.out.println(n.getAddressID("Sheffield")); it returns null. Why this happened even though there are data in my table (see picture).
public ResultSet executeSearch(String q){
openConnection();
try{
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(q);
closeConnection();
return resultSet;
}
catch (Exception e){
JOptionPane.showMessageDialog(null, e.getMessage());
}
finally {
closeConnection();
return null;
}
}
The problem appears to be in your executeSearch method; the finally block will always execute, so by returning null in the finally block, you essentially override what you returned in the try block!
This could be an alternative solution; note that I'm returning at the end of the method instead of within any parts of the try-catch-finally block.
/**
* Converts a provided ResultSet into a generic List so that the
* ResultSet can be closed while the data persists.
* Source: http://stackoverflow.com/a/7507225/899126
*/
public List convertResultSetToList(ResultSet rs) throws SQLException
{
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
List list = new ArrayList(50);
while (rs.next())
{
HashMap row = new HashMap(columns);
for(int i = 1; i <= columns; ++i)
{
row.put(md.getColumnName(i), rs.getObject(i));
}
list.add(row);
}
return list;
}
public List executeSearch(String q)
{
List toReturn;
openConnection();
try {
Statement statement = connection.createStatement();
toReturn = this.convertResultSetToList(statement.executeQuery(q));
}
catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
toReturn = new ArrayList();
}
finally {
closeConnection();
}
return toReturn;
}

JAVA SQL command not properly ended

I have this code:
buy.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent actionEvent)
{
int r;
r = table.getSelectedRow();
String num = (String) table.getValueAt(r, 0);//numele jucariei
//String cop = (String) table.getValueAt(r, 3);//nr de bucati
try
{
pq = stmt.executeQuery("SELECT *" + "FROM buyid_view");
xv = stmt.executeQuery("SELECT toyid, copies " + "FROM alldatas_view" + "WHERE toyname ='"+num+"'");
int buyid = pq.getInt("buyid");
int toyid = xv.getInt("toyid");
int copies = xv.getInt("copies");
copies = copies-1;
CallableStatement cstmt = con.prepareCall("INSERT INTO buy (buyid, toyid)" + "VALUES (?,?)");
cstmt.setInt("buyid", buyid);
cstmt.setInt("toyid", toyid);
ResultSet rs = cstmt.executeQuery();
JOptionPane.showMessageDialog(null, "You brought a toy.");
for(int i = 0; i < table.getRowCount(); i++)
for(int j = 0; j < table.getColumnCount(); j++)
table.setValueAt("", i, j);
try
{
rs = stmt.executeQuery("UPDATE toys set copies "+ copies +"WHERE toyid= '"+toyid+"'");
}
catch (SQLException e)
{
JOptionPane.showMessageDialog(null, e.getMessage());
}
int i = 0;
try
{
rs = stmt.executeQuery("SELECT *"+
"FROM availablebooks_view");
}
catch (SQLException e)
{
e.printStackTrace();
}
finally
{
try {
if(rs.next())
{
table.setValueAt(rs.getString(1), i, 0);
table.setValueAt(rs.getString(2), i, 1);
table.setValueAt(rs.getString(3), i, 2);
i++;
while(rs.next())
{
table.setValueAt(rs.getString(1), i, 0);
table.setValueAt(rs.getString(2), i, 1);
table.setValueAt(rs.getString(3), i, 2);
i++;
}
}
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
}
}
catch (SQLException e)
{
if(e.getMessage().contains("You have to pay!"))
warning(frame, "You didn't pay all your products");
else
warning(frame, e.getMessage());
}
}
});
When I compile my program I don't have any error but when I run it and I click on the buy button it gives me an error saying "ORA-00933: SQL command not properly ended".
When building SQL statements from strings you must ensure there are spaces where spaces are needed.
rs = stmt.executeQuery("SELECT *"+
"FROM availablebooks_view");
The statement you are sending is
SELECT *FROM availablebooks_view
which is invalid syntax. You have this problem in several places in your code.
However, you have a larger issue which results from building your SQL statements piecemeal. This leaves you open to SQL Injection and you should rewrite your code to use prepared statements and parameters instead.
There are multiple errors in your code
First one is
rs = stmt.executeQuery("SELECT *"+
"FROM availablebooks_view");
There is no space between * and FROM, this will actually creates a syntax error
Second one is
rs = stmt.executeQuery("UPDATE toys set copies "+ copies +"WHERE toyid= '"+toyid+"'");
There is no = after set copies, this will also create error.
Third one is
CallableStatement cstmt = con.prepareCall("INSERT INTO buy (buyid, toyid)" + "VALUES (?,?)");
Give space before VALUES

Categories