Update button on stock management system not working, MySQL, Netbeans - java

The update button on my simple stock management system is not updating the stock. When clicked it shows the product updated dialog but nothing happens. It is throwing no errors and i cant find the problem.
It was working when i only had 5 rows but when i added the category and quantity row it stopped.
private void btn_updateActionPerformed(java.awt.event.ActionEvent evt) {
if(checkInputs() && txt_id.getText() != null)
{
String UpdateQuery = null;
PreparedStatement ps = null;
Connection con = getConnection();
//update without image
if(ImgPath == null)
{
try {
UpdateQuery = "UPDATE products SET name = ?, price = ?"
+ ", add_date = ?, category = ?, quantity = ?, WHERE id = ?";
ps = con.prepareStatement(UpdateQuery);
ps.setString(1, txt_name.getText());
ps.setString(2, txt_price.getText());
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String addDate = dateFormat.format(txt_AddDate.getDate());
ps.setString(3, addDate);
ps.setInt(4, Integer.parseInt(txt_id.getText()));
String value = combo_category.getSelectedItem().toString();
ps.setString(5, value);
ps.setString(6, txt_quantity.getText());
ps.executeUpdate();
Show_Products_In_JTable();
JOptionPane.showMessageDialog(null, "Product Updated");
} catch (SQLException ex) {
Logger.getLogger(Main_Window.class.getName()).log(Level.SEVERE, null, ex);
}
}
//update with Image
else{
try{
InputStream img = new FileInputStream(new File(ImgPath));
UpdateQuery = "UPDATE products SET name = ?, price = ?"
+ ", add_date = ?,image = ?, category = ?, quantity = ?, WHERE id = ?";
ps = con.prepareStatement(UpdateQuery);
ps.setString(1, txt_name.getText());
ps.setString(2, txt_price.getText());
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String addDate = dateFormat.format(txt_AddDate.getDate());
ps.setString(3, addDate);
ps.setBlob(4, img);
String value = combo_category.getSelectedItem().toString();
ps.setString(5, value);
ps.setInt(6, Integer.parseInt(txt_id.getText()));
ps.executeUpdate();
Show_Products_In_JTable();
JOptionPane.showMessageDialog(null, "Product Updated");
}catch(Exception ex)
{
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}
}else{
JOptionPane.showMessageDialog(null, "One or More Fields Are Empty Or Wrong");
}
}

At first sight
quantity = ?, WHERE id = ?
shoule be
quantity = ? WHERE id = ?

Related

How to insert multiple records in multiple table using PreparedStatement object in java?

I want to insert two different rows on two other tables. How can I do that? I have read about batch execution but do not understand it clearly. If it is possible to use batch execution, how?
I have tried this way and got this message "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '?, ?, ?, ?, ?, ?)' at line 1
". Thanks in advance.
/**
* save data from multiple tables
*/
private void customSave() {
// create connection
conn = new DB_Connection().makeConn();
try {
// for invoice table
String product_name = comboProductName.getSelectedItem().toString();
String date_of_sale = textDateOfSale.getText();
String paid_on = textPaidOn.getText();
int quantity = Integer.valueOf(spinnerQuantity.getValue().toString());
int discount = Integer.valueOf(textDiscount.getText());
double total_price = Double.valueOf(lblTotal.getText());
// for customer details table
String name = textFullName.getText();
String email = textEmail.getText();
String mobile = textMobile.getText();
String address = textAddress.getText();
stmnt = conn.createStatement();
// save to invoice
String sql_invoice = "INSERT INTO `invoice`(`product_name`, `date_of_sale`, `paid_on`, `discount`, `total_price`, `quantity`) "
+ "VALUES (?, ?, ?, ?, ?, ?)";
ps = conn.prepareStatement(sql_invoice);
ps.setString(1, product_name);
ps.setString(2, date_of_sale);
ps.setString(3, paid_on);
ps.setInt(4, discount);
ps.setDouble(5, total_price);
ps.setInt(6, quantity);
// save to customer_details
String sql_customer = "insert into customer_details(customer_name, email, mobile, address )"
+ "values (?, ?, ?, ?)";
ps = conn.prepareStatement(sql_customer);
ps.setString(1, name);
ps.setString(2, email);
ps.setString(3, mobile);
ps.setString(4, address);
if ((!textDateOfSale.getText().equals("")) && (!textPaidOn.getText().equals(""))
&& (!textFullName.getText().equals(""))) {
int count = ps.executeUpdate(sql_invoice);
int count1 = ps.executeUpdate(sql_customer);
if (count > 0 && count1 > 0) {
JOptionPane.showMessageDialog(null, "Data saved successfully.", "Success!!!",
JOptionPane.INFORMATION_MESSAGE);
textDateOfSale.setText("");
textPaidOn.setText("");
textFullName.setText("");
textEmail.setText("");
textMobile.setText("");
textAddress.setText("");
} else {
JOptionPane.showMessageDialog(null, "Unable to save data.", "Warning!!!",
JOptionPane.WARNING_MESSAGE);
}
} else {
JOptionPane.showMessageDialog(null, "Please fillup the required fields.", "Warning!",
JOptionPane.WARNING_MESSAGE);
}
stmnt.close();
conn.close();
} catch (Exception ex) {
// JOptionPane.showMessageDialog(null, ex, "Error!", JOptionPane.ERROR_MESSAGE);
System.out.println(ex.getMessage());
ex.getStackTrace();
}
}

How to insert (int) and (date) type?

I'd like to insert ID(int), title(varchar), plot(varchar), release_date(date), target(varchar) into exsiting database.
Here is the code which showed no data at all.
How can I add a date type value into a connected database?
else if (e.getSource() == this.insert2) {
String n = this.IDField.getInt();
String m = this.titleField.getText();
String f = this.plotField.getText();
String p = this.release_dateField.getText();
String t = this.targetField.getText();
String[] name = {"MOVIE_ID","title","plot","release_date","main_target"};
this.dt = new DefaultTableModel(name, 0);
/**try~catch*/
try{
stmt.executeUpdate("insert into DB2020_MOVIEINFO values('" + n + "', '" + m + "', '" + f + "', '" + p + "', '" + t + "')");
ResultSet rset_mv = stmt.executeQuery("SELECT * FROM DB2020_MOVIEINFO");
while (rset_mv.next()) {
Object[] data = {rset_mv.getString(1), rset_mv.getString(2), rset_mv.getString(3), rset_mv.getString(4), rset_mv.getString(5)};
dt.addRow(data);
}
}
catch(SQLException se) {
se.printStackTrace();
}
this.jt = new JTable(dt);
jt.getTableHeader().setBackground(Color.decode("#b76e79"));
jt.setSelectionBackground(Color.decode("#f7f6f0"));
this.jsp = new JScrollPane(jt);
jt.setPreferredScrollableViewportSize(new Dimension(800,600));
this.add(centerPanel,BorderLayout.CENTER);
this.centerPanel.removeAll();
this.centerPanel.updateUI();
this.centerPanel.add(jsp);
this.centerPanel.setVisible(true);
}
new code I applied after Mureinik's advise. (I extracted date-part)
else if (e.getSource() == this.insert2) {
Int id = this.IDField.getInt();
String title = this.titleField.getText();
String plot = this.plotField.getText();
String target = this.targetField.getText();
String[] name = {"MOVIE_ID","title","plot","main_target"};
this.dt = new DefaultTableModel(name, 0);
/**try~catch*/
try (PreparedStatement ps =
conn.prepareStatement("insert into DB2020_MOVIEINFO values(?, ?, ?, ?)") {
ps.setInt(1, id); // id should be an int
ps.setString(2, title);
ps.setString(3, plot);
ps.setString(4, target);
}
catch(SQLException se) {
se.printStackTrace();
}
this.jt = new JTable(dt);
jt.getTableHeader().setBackground(Color.decode("#b76e79"));
jt.setSelectionBackground(Color.decode("#f7f6f0"));
this.jsp = new JScrollPane(jt);
jt.setPreferredScrollableViewportSize(new Dimension(800,600));
this.add(centerPanel,BorderLayout.CENTER);
this.centerPanel.removeAll();
this.centerPanel.updateUI();
this.centerPanel.add(jsp);
this.centerPanel.setVisible(true);
}
Instead of trying to force these datatypes to strings, you could use a PreparedStatement and let the JDBC driver do the heavy lifting for you. As a side effect, this will also help protect you application from SQL Injection attacks:
try (PreparedStatement ps =
conn.prepareStatement("insert into DB2020_MOVIEINFO values(?, ?, ?, ?, ?)) {
ps.setInt(1, id); // id should be an int
ps.setString(2, title);
ps.setString(3, plot);
ps.setDate(4, releaseDate); // releaseDate should be java.sql.Date
ps.setString(5, target);
}

Java error: The index out of range when update sql

I have an error when I try to update the record in MSSQL.
My code:
PreparedStatement ps = con.prepareStatement("UPDATE tblUsers SET firstName='?', lastName = '?', phone = ?,"
+ "[group] = ?, picture = ?, address = ? Where id=?");
ps.setString(1, firstName);
ps.setString(2, lastName);
//update phone has two conditions
if (!phone.isEmpty()) {
ps.setString(3, "'" + phone + "'");
} else {
ps.setString(3, null);
}
ps.setInt(4, group);
//update img has two conditions
if (pathImg != null) {
ps.setBytes(5, MyUtils.getImgbinary(pathImg));
} else {
ps.setBytes(5, MyUtils.getImgbinary(defaultPathImg));
}
//update address has two conditions
if (!address.isEmpty()) {
ps.setNString(6, "'" + address +"'");
} else {
ps.setNString(6, null);
}
ps.setInt(7, userID);
When I tried to executeUpdate(), 'The index 6 is out of range' error throws. I don't understand why?
In here, address can be null.

Declaring Scalar variables on sql insert using java

I'm trying to insert into a database, but with the added bonus of checking if there is duplicate data based on 5 fields.
For example I want to insert a line of data but for every ID, it will check 4 other fields, if all 5 fields match I do not want to insert. Other than that, an insert.
So far I have made the sql statement. I tried my query on a database dummy to see if it works and it does but when I run it in java with all the prepared statements, it gives me an error that says "Must declare the scalar variable". Here is my code and I do not know where to declare or what I must declare. Does it depend on the configuration of the database?
System.out.println("connection created successfully using properties file");
PreparedStatement pstmt2 = null;
PreparedStatement pstmt3 = null;
PreparedStatement pstmt5 = null;
PreparedStatement pstmt6 = null;
ResultSet rs = null;
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(
"C:\\Users\\darroyo\\Documents\\pruebasx.txt"));
} catch (FileNotFoundException e1) {
logger.error(e1.getMessage());
}
String line = null;
try {
line = reader.readLine();
} catch (IOException e1) {
logger.error(e1.getMessage());
}
String query = " insert into FRONTMC.HECHO (folio_hecho, folio_orden,"
+ "clave_sentido, titulos_hecho, precio, importe, liquidacion, contraparte, id_estatus, isin, contrato,"
+ "secondary_exec_id, exec_id, F11_ClOrdID, fecha_recepcion, fecha_sentra,emisora,serie)"
+ " select ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,convert(varchar(30),cast(? as datetime),120),convert(varchar(30),cast(? as datetime),120),?,?"
+" from FRONTMC.HECHO WHERE NOT EXISTS (SELECT * FROM FRONTMC.HECHO WHERE ISIN = ?"
+ "AND EMISORA = ? AND SERIE = ? AND CLAVE_SENTIDO = ? AND SECONDARY_EXEC_ID =?";
PreparedStatement preparedStmt = null;
try {
preparedStmt = con.prepareStatement(query);
} catch (SQLException e1) {
logger.error(e1.getMessage());
}
Map<Integer,String> hm1 = new HashMap<Integer,String>();
try {
do {
try{
String[] tokens = line.split("");
for (int i = 0; i != tokens.length; i++) {
int dataIndex = tokens[i].indexOf('=') + 1;
String data = tokens[i].substring(dataIndex);
hm1.put(new Integer(i),data);
}
String query2 = "select emisora from FRONTMC.EMISORA_CUSTODIO_SIGLO where isin = ?";
String query5 = " insert into FRONTMC.HECHO (emisora)"
+ " values ( ?)";
pstmt2 = con.prepareStatement(query2);
pstmt5 = con.prepareStatement(query5);
String query3 = "select serie from FRONTMC.EMISORA_CUSTODIO_SIGLO where isin = ?";
String query6 = " insert into FRONTMC.HECHO (emisora)"
+ " values ( ?)";
pstmt3 = con.prepareStatement(query3); // create a statement
pstmt6 =con.prepareStatement(query6);
setParameterString(preparedStmt,1, hm1.get(23));
setParameterString(preparedStmt,2, hm1.get(19));
setParameterString(preparedStmt,3, hm1.get(15));
setParameterString(preparedStmt,4, hm1.get(30));
setParameterString(preparedStmt,5, hm1.get(16));
setParameterString(preparedStmt,6, hm1.get(18));
setParameterString(preparedStmt,7, hm1.get(8));
setParameterString(preparedStmt,8, hm1.get(33));
setParameterString(preparedStmt,9, hm1.get(27));
setParameterString(preparedStmt,10, hm1.get(17));
setParameterString(preparedStmt,11, hm1.get(26));
setParameterString(preparedStmt,12, hm1.get(23));
setParameterString(preparedStmt,13, hm1.get(10));
setParameterString(preparedStmt,14, hm1.get(14));
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd");
SimpleDateFormat sdf2 = new SimpleDateFormat("dd/MM/yyyy");
String ds2 = null;
ds2 = sdf2.format(sdf1.parse(hm1.get(6)));
String newfecha1 = ds2;
setParameterString(preparedStmt,15, newfecha1);
SimpleDateFormat sdf3 = new SimpleDateFormat("yyyyMMdd");
SimpleDateFormat sdf4 = new SimpleDateFormat("dd/MM/yyyy");
String ds4 = null;
ds4 = sdf4.format(sdf3.parse(hm1.get(6)));
String newfecha3 = ds4;
setParameterString(preparedStmt,16, newfecha3);
pstmt2.setString(1, hm1.get(17));
rs = pstmt2.executeQuery();
while (rs.next()) {
String emisora = rs.getString(1);
pstmt5.setString(1,emisora);
setParameterString(preparedStmt,17, emisora);
pstmt3.setString(1, hm1.get(17));
rs = pstmt3.executeQuery();
while (rs.next()) {
String serie = rs.getString(1);
pstmt6.setString(1,serie);
System.out.println(serie);
setParameterString(preparedStmt,18, serie);
setParameterString(preparedStmt,19, hm1.get(17));
setParameterString(preparedStmt,20, emisora);
setParameterString(preparedStmt,21, serie);
setParameterString(preparedStmt,22, hm1.get(15));
setParameterString(preparedStmt,23, hm1.get(23));
preparedStmt.execute();
}
}}catch(Exception ab){
new Thread(new Runnable(){
#Override
public void run(){
errorcon2();
}
}).start();
logger.error(ab.getMessage());
System.out.println(ab.getMessage());
ab.printStackTrace();
}
}while ((line = reader.readLine()) != null);}
catch(Exception a){
logger.error(a.getMessage());
}
new Thread(new Runnable(){
#Override
public void run(){
exitomsj();
}
}).start();
Here is the exception I get: Mistranslation it is not scalable, it is scalar.
com.microsoft.sqlserver.jdbc.SQLServerException: Debe declarar la variable escalar "#P18AND".
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:217)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1655)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:440)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:385)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:7505)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:2445)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:191)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:166)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.execute(SQLServerPreparedStatement.java:367)
at swt.swtapp2$2.mouseDown(swtapp2.java:488)
at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:193)
at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4418)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1079)
at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4236)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3824)
at org.eclipse.jface.window.Window.runEventLoop(Window.java:818)
at org.eclipse.jface.window.Window.open(Window.java:794)
at swt.swtapp2.main(swtapp2.java:610)
You are missing a space.
+ "AND EMISORA = ? AND ...
should be
+ " AND EMISORA = ? AND ...

Insert data from jTable into Database

I am trying to save some JTable Data into Database: My code is like this:
public void save(){
String invSL = new Mixed_Calculation().invoice_Sl();
jTextField6.setText(invSL);
int rows = jTable1.getRowCount();
for(int row = 0; row<rows ; row++){
String code = (String) jTable1.getValueAt(row, 1);
String name = (String) jTable1.getValueAt(row, 2);
String unit = (String) jTable1.getValueAt(row, 3);
String units[] = unit.split(" ");
int q = Integer.parseInt(units[0]);
String u = units[1];
String rate = (String) jTable1.getValueAt(row, 4);
String total = (String) jTable1.getValueAt(row, 5);
String d_rat = (String) jTable1.getValueAt(row, 6);
String discount = (String) jTable1.getValueAt(row, 7);
String net = (String) jTable1.getValueAt(row, 8);
try{
conn = new connection().db();
conn.setAutoCommit(false);
String query = "INSERT INTO INVOICE(INVOICE_NO, CODE, DESCRIPTION, BONUSABLE,"
+ " TAXABLE, CATEGORY, QNTY, UNIT, RATE, TOTAL , DISC_PERCENTAGE, DISCOUNT, NET_AMOUNT ) "
+ " VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " ;
stmt = conn.prepareStatement(query);
stmt.setString(1, jTextField6.getText()); //Invoice No
stmt.setString(2, code); //Code
stmt.setString(3, name); //Description
stmt.setString(4, ""); //Bonusable
stmt.setString(5, ""); //Taxable
stmt.setString(6, ""); //Category
stmt.setInt(7, q); //Qnty
stmt.setString(8, u); //Unit
stmt.setDouble(9, Double.parseDouble(rate)); //Rate
stmt.setDouble(10, Double.parseDouble(total)); //Total
stmt.setDouble(11, Double.parseDouble(d_rat)); //Disc_%
stmt.setDouble(12, Double.parseDouble(discount)); //Discount
stmt.setDouble(13, Double.parseDouble(net)); //net_Amount
stmt.addBatch(); stmt.executeBatch();
conn.commit();
}
catch(SQLException ex){
JOptionPane.showMessageDialog(null, "Cannot save. "+ ex);
}
finally{try{stmt.close(); conn.close(); conn.setAutoCommit(true);} catch(SQLException ex){} }
}
}
Why this method has no effect at all ? Am I doing something wrong here ? Is there any other system, that I can insert data directly from jTable ?
Take the execution of the batch outside the for-loop, that's the benefit of addBatch() as it hits the database only one time when executeBatch() is called.
for(int row = 0; row<rows ; row++)
{
//......
stmt.addBatch();
}
stmt.executeBatch();
conn.commit();

Categories

Resources