Deducting Stock - java

I have a JTable which acts as an order pane. When I complete an order and click a JButton called "New Order" it clears the JTable and it also clears the order specifics such as price and change etc. What I am trying to do when I click the "New Order" JButton is to deduct the stock that was sold in the last order before it was cleared.
I have a table in my SQL database with products which have columns called:
ProductID (PK), ProductName, ProductDescrp, Type, SupplierName, Quantity, Price
My goal in all of this is to reduce the Quantity in stock in the database on any product that has been sold in an order. This is my code so far.
jbtNewOrder.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if(e.getSource().equals(jbtNewOrder))
{
total = 0.0;
totalTF.setText("");
tenderedTF.setText("");
changeTF.setText("");
model.setRowCount(0);
try
{
int prodID = 0;
String sql = ("UPDATE product " + "SET Quantity = Quantity -1" + (getDBQuantity(prodID)-1) + " WHERE ProductID = " + prodID);
databaseUpdate(sql);
}
catch(Exception e1)
{
e1.printStackTrace();
}
return status;
}
// return quantity of a product in DB
public int getDBQuantity(int prodID)
{
int quantity=0;
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = (Connection) DriverManager.getConnection(DB_URL, USER_NAME, PASSWORD);
statement = (Statement) conn.createStatement();
resultSet = statement.executeQuery("select Quantity from team_project.product WHERE ProductID = " + prodID);
while (resultSet.next())
{
quantity = (resultSet.getInt("Quantity"));
}
conn.close();
}catch(Exception e)
{
e.printStackTrace();
}
return quantity;
}}
private int databaseUpdate(String sqlUpdate)
{
int status = 0;
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = (Connection) DriverManager.getConnection(DB_URL, USER_NAME, PASSWORD);
statement = conn.createStatement();
status = statement.executeUpdate(sqlUpdate);
conn.close();
}
catch (Exception e) {
e.printStackTrace();
}
return status;
}

Related

Using two combobox to set conditions for a search in a database and displaying in jtable

I need to display the details of students in a particular stream of a schoolclass in Jtable from a database containing all the names of students in the school. I have two jComboboxes, on to select which class and the other to select the stream. I am asking for a way to define these two conditions in order to display all the students in a particular stream in a jtable. I apologize in advance if my code is messy.
public Classes() {
initComponents();
show_student();
}
public Connection getConnection() {
Connection con = null;
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sms", "root", "");
} catch(Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
return con;
}
public ArrayList<Individualclass> studentList(String ValToSearch) {
ArrayList<Individualclass> list = new
ArrayList<Individualclass>();
Statement st;
ResultSet rs;
try {
Connection con=getConnection();
st = con.createStatement();
String searchQuery = "SELECT * FROM `students` WHERE CONCAT(`firstName`, `surname`, `otherNames`, `regNo`) LIKE '%"+ValToSearch+"%'";
rs = st.executeQuery("searchQuery ");
Individualclass ic;
while(rs.next()) {
ic = new Individualclass(
rs.getString("firstName"),
rs.getString("surname"),
rs.getString("otherNames"),
rs.getInt("regNo")
);
list.add(ic);
}
} catch(Exception ex){
JOptionPane.showMessageDialog(null, ex.getMessage());
}
return list;
}
public void findStudents() {
}
private void sClassActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sClassActionPerformed
try {
Connection con = getConnection();
String fetch_row = "SELECT * FROM students where sClass=?";
PreparedStatement pst = con.prepareStatement(fetch_row);
pst.setString(1, (String) sClass.getSelectedItem());
ResultSet rs = pst.executeQuery();
while(rs.next()) {
Individualclass ic = new Individualclass(rs.getString("firstName"),rs.getString("surname"),rs.getString("otherNames"),rs.getInt("regNo"));
}
} catch(Exception ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}//GEN-LAST:event_sClassActionPerformed
private void streamActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_streamActionPerformed
try {
Connection con = getConnection();
String fetch_row = "SELECT * FROM students where stream=?";
PreparedStatement pst = con.prepareStatement(fetch_row);
pst.setString(1, (String)stream.getSelectedItem());
ResultSet rs = pst.executeQuery();
while(rs.next()) {
Individualclass ic = new Individualclass(rs.getString("firstName"),rs.getString("surname"),rs.getString("otherNames"),rs.getInt("regNo"));
}
} catch(Exception ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}//GEN-LAST:event_streamActionPerformed
public void show_student() {
ArrayList<Individualclass> list = new ArrayList<Individualclass>();
DefaultTableModel model = (DefaultTableModel)jTable_Display_Student.getModel();
Object [] row = new Object[13];
for(int i = 0; i < list.size(); i++) {
row[0] = list.get(i).getFirstName();
row[1] = list.get(i).getsurname();
row[2] = list.get(i).getOtherNames();
row[3] = list.get(i).getregNo();
model.addRow(row);
}
}

java.sql.SQLExecption:parameter index out of range (1>number of prameters, which is 0) for update sql

i have problem with my project, and it still new for me with MYSQL, i want to get data from database and do some calculation and update the value on it,
its like making withdraw function like ATM machine. This my table look like.
enter image description here . You can see constructor parameter that carry value (String value and String ID). For Value="100"; and ID="5221311" you can see it on my table picture.
public ConformWithdraw() {
initComponents();
try {
Class.forName("com.jdbc.mysql.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:/atm", "root", "");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public ConformWithdraw(String value,String ID) {
initComponents();
this.value=value;
this.ID=ID;
}
------------------------------------------------------------
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/atm?zeroDateTimeBehavior=convertToNull", "root", "");
String validate = "SELECT * FROM customer_details WHERE accountID LIKE '" + ID
+ "'";
PreparedStatement smtm = con.prepareStatement(validate);
ResultSet resultSet = smtm.executeQuery();
User user = null;
if (resultSet.next()) {
user = new User();
user.setBalance(resultSet.getString("accountBalance"));
double balance=Double.parseDouble(user.getBalance());
double val=Double.parseDouble(value);
total =(balance - val);
}
smtm.close();
resultSet.close();
program();
} catch (SQLException | HeadlessException | ClassCastException ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
-------------------------------------------------------------
public void program(){
String sqlUpdate = "UPDATE customer_details "
+ "SET accountBalance = '"+String.valueOf(total)+"'"
+ "WHERE accountID = '"+ID+"'";
try{
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/atm?zeroDateTimeBehavior=convertToNull", "root", "");
PreparedStatement pstmt = con.prepareStatement(sqlUpdate);
id=Integer.parseInt(ID);
pstmt.setString(1, String.valueOf(total));
pstmt.setInt(2, id);
int rowAffected = pstmt.executeUpdate();
pstmt.close();
new ShowWithdraw().setVisible(true);
dispose();
}catch(SQLException | HeadlessException | ClassCastException ex){
JOptionPane.showMessageDialog(null, ex);
JOptionPane.showMessageDialog(null, "slh sini");
}
}
You are already setting the parameters on the query, so It tries to set the parameters and find no parameters to find. Try this:
String sqlUpdate = "UPDATE customer_details "
+ "SET accountBalance = ?"
+ "WHERE accountID = ?";

JavaFX - Insert form textfield to SQLite Database

I made a Form scene in my Application and wanted to insert the entered data to my SQLite Database when I hit the Save button. Here is the short code:
#FXML
private void handleSaveNewShop(ActionEvent event) {
String name = shopname.getText();
String adress = streetadress.getText();
String city = cityname.getText();
String state = statename.getText();
String country = countryname.getText();
String zip = zipcode.getText();
String phonept1 = phonecountryid.getText();
String phonept2 = phoneareaid.getText();
String phonept3 = phoneothernumber.getText().toString();
Connection conn = null;
Statement stmt = null;
try{
Class.forName("org.sqlite.JDBC");
System.out.print("\nConnecting to database...");
conn = DriverManager.getConnection("jdbc:sqlite:FranchiseManagement.sqlite");
System.out.println(" SUCCESS!\n");
/*Tried this
String insertToshopList = "INSERT INTO shopList (name, adress, city, state, country, zipcode, phonect, phonearea, phonemain)" + "values(name,adress,city,state,country,zip,phonept1,phonept2,phonept3)";
stmt.executeUpdate(insertToshopList);
*/
//And This
//stmt.executeUpdate( "INSERT INTO shopList ('name','adress','city', 'state', 'country', 'zipcode', 'phonect', 'phonearea', 'phonemain') VALUES('"+name+"','"+adress+"','"+city+"'),'"+state+"','"+country+"','"+zip+"','"+phonept1+"','"+phonept2+"','"+phonept3+"'");
conn.commit();
System.out.println(" SUCCESS!\n");
conn.close();
} catch(SQLException se) {
se.printStackTrace();
}
catch(Exception e) {
e.printStackTrace();
}
But I got NullPointException on my commited parts. The database connection seems okay and Connected.
Here is how my Database Looks:
Fixed it by removing the commit and added the INSERT into method well-formatted:
#FXML
private void handleSaveNewShop(ActionEvent event) {
String name = shopname.getText();
String adress = streetadress.getText();
String city = cityname.getText();
String state = statename.getText();
String country = countryname.getText();
String zip = zipcode.getText();
String phonept1 = phonecountryid.getText();
String phonept2 = phoneareaid.getText();
String phonept3 = phoneothernumber.getText();
Connection conn;
Statement stmt = null;
try{
Class.forName("org.sqlite.JDBC");
System.out.print("\nConnecting to database...");
conn = DriverManager.getConnection("jdbc:sqlite:FranchiseManagement.sqlite");
System.out.println(" SUCCESS!\n");
stmt = conn.createStatement();
stmt.executeUpdate( "INSERT INTO shopList ('name','adress','city', 'state', 'country', 'zipcode', 'phonect', 'phonearea', 'phonemain') VALUES('"+name+"','"+adress+"','"+city+"','"+state+"','"+country+"','"+zip+"','"+phonept1+"','"+phonept2+"','"+phonept3+"')");
//conn.commit();
System.out.println(" SUCCESS!\n");
conn.close();
} catch (ClassNotFoundException | SQLException e){
Logger.getLogger(DBConnect.class.getName()).log(Level.SEVERE, null, e);
}

java JDBC ArrayIndexOutOfBoundsException when delete, update

So i try to create a JTable which connect to SQL server database by JBDC, and have a function like insert, delete, and edit the data. It work well with insert but update, delete. Can you guys show me why i got ArrayIndexOutOfBoundsException: -1 and how to fix it. Here 's my code. Book here is a class extends JFRAME
public Book() {
initComponents();
model.addColumn("ID");
model.addColumn("Name");
model.addColumn("Type");
jTable1.setModel(model);
displayTable();
jTable1.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
int row = jTable1.getSelectedRow();
txtName.setText(jTable1.getValueAt(row, 1).toString());
txtType.setText(jTable1.getValueAt(row, 2).toString());
}
});
}
public void displayTable() {
try {
model.setRowCount(0);
ConnectToSQL sql = new ConnectToSQL();
connection = sql.getConnection();
st = connection.createStatement();
ResultSet result = st.executeQuery("SELECT * FROM BOOK");
while (result.next()) {
model.addRow(new Object[]{result.getInt("id"), result.getString("name"), result.getString("type")});
}
} catch (SQLException ex) {
Logger.getLogger(Book.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
int row = jTable1.getSelectedRow();
String id = jTable1.getValueAt(row, 0).toString();
try {
// TODO add your handling code here:
st.executeUpdate("Update Book set name ='" + txtName.getText() + "',type='" + txtType.getText() + "' where id =" + id);
displayTable();
} catch (SQLException ex) {
Logger.getLogger(Book.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
int row = jTable1.getSelectedRow();
String id = jTable1.getValueAt(row, 0).toString();
try {
// TODO add your handling code here:
st.executeUpdate("Delete from book where id =" + id);
displayTable();
} catch (SQLException ex) {
Logger.getLogger(Book.class.getName()).log(Level.SEVERE, null, ex);
}
}
You get this error, because you don't select any row, so to avoid this problem you have to use :
if(jTable1.getSelectedRow() != -1){
int row = jTable1.getSelectedRow();
String id = jTable1.getValueAt(row, 0).toString();
//rest of your code here
}else{
//show an error for example, no row is selected
}
Note
Instead of :
st.executeUpdate("Update Book set name ='" + txtName.getText() + "',type='" + txtType.getText() + "' where id =" + id);
You have to use PreparedStatement to avoid any syntax error or SQL Injection
For example :
String query = "Update Book set name = ?, type=? where id =?";
try (PreparedStatement update = connection.prepareStatement(query)) {
update.setString(1, txtName.getText());
update.setString(2, txtType.getText());
update.setInt(3, id);
update.executeUpdate();
}
Another thing, your id is an int so you can't set a String to your query like you do you have to set an int :
String id = jTable1.getValueAt(row, 0).toString();
Instead you have to use :
int id = Integer.parseInt(jTable1.getValueAt(row, 0).toString());

Inserting issue into the database via java

I have a bit of a problem with inserting some data in the database. The data is being read by an CSV parser and changed to data besides that, I continue to get this error message:
Connected to the PostgreSQL server successfully.
Naam van de garage: P_Erasmusbrug, Longditude: 4.482313155, Latitude: 51.91024645
org.postgresql.util.PSQLException: The column index is out of range: 1, number of columns: 0.
at org.postgresql.core.v3.SimpleParameterList.bind(SimpleParameterList.java:65)
at org.postgresql.core.v3.SimpleParameterList.setStringParameter(SimpleParameterList.java:128)
at org.postgresql.jdbc.PgPreparedStatement.bindString(PgPreparedStatement.java:1023)
at org.postgresql.jdbc.PgPreparedStatement.setString(PgPreparedStatement.java:374)
at org.postgresql.jdbc.PgPreparedStatement.setString(PgPreparedStatement.java:358)
at Database.ConnectDatabase.parser(ConnectDatabase.java:80)
at Events.CSVReader.main(CSVReader.java:40)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Thank you for your service.
Naam van de garage: P_St.Jacobsplaats, Longditude: 4.482054381, Latitude: 51.92410235
Thank you for your service.
Naam van de garage: P_Schouwburgplein, Longditude: 4.473618335, Latitude: 51.92102728
org.postgresql.util.PSQLException: The column index is out of range: 1, number of columns: 0.
Which continues for all the other lines of data. Is there maybe a way to fix this as I don't really understand what the error message includes..
The a, b2, and c2 are variables for the ''name'' , ''londitude'' and ''latitude''.
package Database;
import java.io.*;
import java.sql.*;
import java.util.HashMap;
import java.sql.SQLException;
public class ConnectDatabase {
private final String url = "jdbc:postgresql://localhost/Project3";
private final String user = "postgres";
private final String password = "kaas123";
private Connection conn;
public Connection connect() {
Connection conn = null;
try {
conn = DriverManager.getConnection(url, user, password);
System.out.println("Connected to the PostgreSQL server successfully.");
} catch (SQLException exception) {
System.out.println(exception.getMessage());
}
this.conn = conn;
return conn;
}
public HashMap getGarages() {
HashMap<String, Double> newHashMap = new HashMap<String, Double>();
try {
Statement stmt = conn.createStatement();
ResultSet rs;
rs = stmt.executeQuery("SELECT deelgemeente, COUNT(garagenaam) FROM garages GROUP BY deelgemeente");
while (rs.next()) {
String deelGemeenteNaam = rs.getString("deelgemeente");
double garageNaamCount = rs.getDouble("COUNT");
newHashMap.put(deelGemeenteNaam, garageNaamCount);
}
} catch (Exception e) {
System.err.println("Got an exception!");
System.err.println(e.getMessage());
}
return newHashMap;
}
public HashMap getTheftYear(int year) {
HashMap<String, Double> newHashMap = new HashMap<String, Double>();
try {
Statement stmt = conn.createStatement();
ResultSet rs;
rs = stmt.executeQuery("SELECT deelgemeente, percentagediefstal FROM autodiefstal WHERE jaar = " + year);
while (rs.next()) {
String deelGemeenteNaam = rs.getString("deelgemeente");
double deelPercentage = rs.getDouble("percentagediefstal");
newHashMap.put(deelGemeenteNaam, deelPercentage);
}
} catch (Exception e) {
System.err.println("Got an exception!");
System.err.println(e.getMessage());
}
return newHashMap;
}
public int parser(String a, float b2, float c2) {
int updated = 0;
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = DriverManager.getConnection(url, user, password);
String insertSQL = "INSERT INTO testparser(garagenaam, xpos, ypos) VALUES(" + a + "," + b2 + "," + c2 + ")";
stmt = conn.prepareStatement(insertSQL);
stmt.setString(1, a);
stmt.setFloat(2, b2);
stmt.setFloat(3, c2);
System.out.println("Inserted data into the database...");
updated = stmt.executeUpdate();
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (stmt != null)
conn.close();
} catch (SQLException se) {
}
try {
if (conn != null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
System.out.println("Thank you for your service.");
this.conn = conn;
return updated;
}
}
You aren't correctly using the ? placeholders system, replace :
String insertSQL = "INSERT INTO testparser(garagenaam, xpos, ypos) VALUES(" + a + "," + b2 + "," + c2 + ")";
with
String insertSQL = "INSERT INTO testparser(garagenaam, xpos, ypos) VALUES(?,?,?)";

Categories