My program is used to display the textfield values and date to a table in java and saves the table value to MySQL database. The textfiled and dateChooser data is displayed in the table and saved in one click of a button
DefaultTableModel model = (DefaultTableModel) jTable2.getModel();
model.addRow(new Object[]
{((JTextField) invo_date.getDateEditor().getUiComponent()).getText(),
((JTextField) invo_date1.getDateEditor().getUiComponent()).getText(),
dec.getText(), BL.getText()});
conn = JavaDb.ConnectDB();
int p = 0;
if (p == 0) {
try {
int rows = jTable2.getRowCount();
String queryco = "update into status(date, to_date, description, containers) values( ?,?,?,?)";
pst = conn.prepareStatement(queryco);
for (int row = 0; row < rows; row++) {
String datee = (String) jTable2.getValueAt(row, 0);
String mpakadates = (String) jTable2.getValueAt(row, 1);
String descri = (String) jTable2.getValueAt(row, 2);
String total = (String) jTable2.getValueAt(row, 3);
String container = (String) jTable2.getValueAt(row, 4);
pst.setString(1, datee);
pst.setString(2, mpakadates);
pst.setString(3, descri);
pst.setString(4, total);
pst.setString(5, container);
pst.addBatch();
}
pst.executeBatch();
pst.execute();
JOptionPane.showMessageDialog(this, "Data Saved Successfully");
st.close();
} catch (Exception e) {
System.err.println("Got an exception! " + e);
System.err.println(e.getMessage());
}
}
Related
I want to get the last inserted id but it has a prefix on it like for example "SIN0000001"
and when I enter this code it creates an error that says No value specified for parameter 1.
It should pop up a GUI which says
Successfully recorded!
but it only saves the data directly to the database and outputs an error.
Succesfully recorded!
I've also used triggers in my database to have prefixes in my id.
These are my two tables.
sales and sales_seq
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MM/dd/yyyy");
LocalDateTime now = LocalDateTime.now();
String date = dtf.format(now);
String amount_due = jTextField_amountDuePayment.getText();
String cash = jTextField_cash.getText();
String balance = jTextField_balance.getText();
int lastid = 0;
try {
String sale_query = "INSERT INTO dnk_database.sales (`date`, `amount_due`, `cash`, `balance`) VALUES (?,?,?,?);";
pst = con.prepareStatement(sale_query, Statement.RETURN_GENERATED_KEYS);
pst.setString(1, date);
pst.setString(2, amount_due);
pst.setString(3, cash);
pst.setString(4, balance);
pst.executeUpdate();
ResultSet generatedKeyResult = pst.getGeneratedKeys();
if(generatedKeyResult.next()){
lastid = generatedKeyResult.getInt(1);
}
Sell sell = new Sell();
int rows = sell.jTable_itemList.getRowCount();
String product_query = "INSERT INTO dnk_database.product_sales (`sales_number`, `product_barcode`, `sell_price`, `quantity`, `total`) VALUES (?,?,?,?,?);";
pst = con.prepareStatement(product_query);
String product_barcode = "";
String price = "";
String qty = "";
int total = 0;
for(int i = 0; i < sell.jTable_itemList.getRowCount(); i++){
product_barcode = (String)sell.jTable_itemList.getValueAt(i, 0);
price = (String)sell.jTable_itemList.getValueAt(i, 2);
qty = (String)sell.jTable_itemList.getValueAt(i, 3);
total = (int)sell.jTable_itemList.getValueAt(i, 4);
pst.setInt(1, lastid);
pst.setString(2, product_barcode);
pst.setString(3, price);
pst.setString(4, qty);
pst.setInt(5, total);
pst.executeUpdate();
}
pst.addBatch();
JOptionPane.showMessageDialog(this, "Succesfully recorded!");
} catch (SQLException ex) {
Logger.getLogger(Payment.class.getName()).log(Level.SEVERE, null, ex);
}
}
I am trying to update a database using input from user and saving it in jtable, then using jtable I am updating the database, but I am not able to get fetch and update 2nd row in database.
please suggest a solution, Thanks in advance.
try {
Class.forName("com.mysql.jdbc.Driver");
con = myconnection.getConnection();
String name;
for (int i = 0; i < jTable2.getRowCount(); i++) {
name = (String) jTable2.getModel().getValueAt(i, 0);
String abcd = "select * from medicine where Name=? ";
stmt = conn.prepareStatement(abcd);
stmt.setString(1, name);
rs = stmt.executeQuery();
if (rs.next()) {
name = (String) jTable2.getModel().getValueAt(i, 0);
String stock = rs.getString("qty");
int nowstock = Integer.parseInt(stock);
int qty1 = Integer.parseInt(jTable2.getValueAt(i, 2).toString());
int newstock = nowstock - qty1;//Integer.parseInt(jTable2.getValueAt(i, 2).toString());
String sqlupdate = "UPDATE medicine SET qty='" + newstock + "'WHERE Name='" + name + "' "; //
stmt = conn.prepareStatement(sqlupdate);
stmt.executeUpdate();
}
}
} catch (ClassNotFoundException ex) {
Logger.getLogger(Bill.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(Bill.class.getName()).log(Level.SEVERE, null, ex);
}
The select serves no purpose, and you can just iterate all names and update directly:
for (int i=0; i < jTable2.getRowCount(); i++) {
String name = (String) jTable2.getModel().getValueAt(i, 0);
int qty1 = Integer.parseInt(jTable2.getValueAt(i, 2).toString());
String update = "UPDATE medicine SET qty = qty - ? WHERE Name = ?";
PreparedStatement ps = conn.prepareStatement(update);
ps.setInt(1, qty1);
ps.setString(2, name);
ps.executeUpdate();
}
If your JTable happens to have more than say 10 or so names, then a more efficient way to do this would be to use a single update with a WHERE IN clause containing all names which appear in the table, i.e.
UPDATE medicine SET qty = qty - ? WHERE Name IN (...);
I need to insert only one column data from jtable to DB mysql,I found a way to do it but i'm facing a problem which occur when i inserted less data than expected eg: insert 2 rows instead of 3 rows; Error:java.lang.arrayindexoutofboundsexception 2>=2
How do I get rid of this ?
You can check out my code down ...Thanks
try
{
//String product3 = "null";
int rows = jTable1.getRowCount();
int cols = jTable1.getColumnCount();
String salesql = "insert into salling(orderid,saledate,prod1,prod2,prod3,tax,subtotal,total) values(?,?,?,?,?,?,?,?)";
pst = conn.prepareStatement(salesql);
pst.setString(1, jTextFieldOrderNo.getText());
pst.setString(2, jTextFieldDate.getText());
for(int row =0; row <= rows; row++)
{
String product1 = (String)jTable1.getValueAt(0, 0);
String product2 = (String)jTable1.getValueAt(1, 0);
String product3 = (String)jTable1.getValueAt(2, 0);
// String product3 = (String)jTable1
pst.setString(3, product1);
pst.setString(4, product2);
pst.setString(5, product3);
}
pst.setString(6, jTextFieldTax.getText());
pst.setString(7, jTextFieldSuTotal.getText());
pst.setString(8, jTextFieldTotal.getText());
pst.execute();
JOptionPane.showMessageDialog(null, "Data saved...");
}catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
}
is it possible to update multiple rows in jtable using batch.. if yes then how? if not is there any other solution? i mean update statement here not insert!
thanx in advance
try {
int rows = jTable1.getRowCount();
cc.c.setAutoCommit(false);
String sql = "Insert into employyes(idemployyes,employyesName,employyesAge,employyesAddress) values (?,?,?,?)";
cc.pst = cc.c.prepareStatement(sql);
for (int row = 0; row < rows; row++) {
String idemployyes = (String) jTable1.getValueAt(row, 0);
String employyesName = (String) jTable1.getValueAt(row, 1);
String employyesAge = (String) jTable1.getValueAt(row, 2);
String employyesAddress = (String) jTable1.getValueAt(row, 3);
cc.pst.setString(1, idemployyes);
cc.pst.setString(2, employyesName);
cc.pst.setString(3, employyesAge);
cc.pst.setString(4, employyesAddress);
cc.pst.addBatch();
cc.pst.executeBatch();
cc.c.commit();
}
} catch (SQLException e) {
JOptionPane.showMessageDialog(this, e.getMessage());
}
here is the answer:
try {
int rows = jTable1.getRowCount();
cc.c.setAutoCommit(false);
String sqlquery = "UPDATE employyes\n"
+ "SET employyesName = ?,employyesAge = ?, employyesAddress = ?\n"
+ "WHERE idemployyes = ?;";
cc.pst = cc.c.prepareStatement(sqlquery);
for (int row = 0; row < rows; row++) {
String idemployyes = (String) jTable1.getValueAt(row, 0);
String employyesName = (String) jTable1.getValueAt(row, 1);
String employyesAge = (String) jTable1.getValueAt(row, 2);
String employyesAddress = (String) jTable1.getValueAt(row, 3);
cc.pst.setString(1, employyesName);
System.out.println(employyesName);
cc.pst.setString(2, employyesAge);
System.out.println(employyesAge);
cc.pst.setString(3, employyesAddress);
System.out.println(employyesAddress);
cc.pst.setString(4, idemployyes);
System.out.println(idemployyes);
cc.pst.addBatch();
cc.pst.executeBatch();
cc.c.commit();
}
} catch (SQLException e) {
JOptionPane.showMessageDialog(this, e.getMessage());
}
I am trying to save Multiple row data from JTable into Database, Here is my code for reference:
try{
int rows=tblCO2.getRowCount();
for(int row = 0; row<rows; row++)
{
String coitemname = (String)tblCO2.getValueAt(row, 0);
String cocateg = (String)tblCO2.getValueAt(row, 1);
String codesc = (String)tblCO2.getValueAt(row, 2);
String coloc = (String)tblCO2.getValueAt(row, 3);
String coitemtagno = (String)tblCO2.getValueAt(row, 4);
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/iotams",user,pass);
conn.setAutoCommit(false);
String queryco = "Insert into tblcheckout(CheckoutID,ItemTagNo,ItemName,Category,Description,Location) values (?,?,?,?,?)";
pst = conn.prepareStatement(queryco);
pst.setString(1, coitemname);
pst.setString(2, cocateg);
pst.setString(3, codesc);
pst.setString(4, coloc);
pst.setString(5, coitemtagno);
pst.addBatch();
}
catch(Exception e)
{
}
}
pst.executeBatch();
conn.commit();
}
catch(Exception e){
JOptionPane.showMessageDialog(this,e.getMessage());
}
The Problem is, it is only inserting one row data into database. Can someone please help me? :( thanks!
Remove following line codes from loop and place before loop
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/iotams",user,pass);
conn.setAutoCommit(false);
String queryco = "Insert into tblcheckout(CheckoutID,ItemTagNo,ItemName,Category,Description,Location) values (?,?,?,?,?)";
pst = conn.prepareStatement(queryco);
Example: Replace your code by following code
try{
int rows=tblCO2.getRowCount();
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/iotams",user,pass);
conn.setAutoCommit(false);
String queryco = "Insert into tblcheckout(CheckoutID,ItemTagNo,ItemName,Category,Description,Location) values (?,?,?,?,?)";
pst = conn.prepareStatement(queryco);
for(int row = 0; row<rows; row++)
{
String coitemname = (String)tblCO2.getValueAt(row, 0);
String cocateg = (String)tblCO2.getValueAt(row, 1);
String codesc = (String)tblCO2.getValueAt(row, 2);
String coloc = (String)tblCO2.getValueAt(row, 3);
String coitemtagno = (String)tblCO2.getValueAt(row, 4);
pst.setString(1, coitemname);
pst.setString(2, cocateg);
pst.setString(3, codesc);
pst.setString(4, coloc);
pst.setString(5, coitemtagno);
pst.addBatch();
}
pst.executeBatch();
conn.commit();
}
catch(Exception e){
JOptionPane.showMessageDialog(this,e.getMessage());
}
Then run it think it work.
For Batch insert example is here https://my.vertica.com/docs/5.0/HTML/Master/14878.htm
the code above is not able to run in netbeans ,
However I made a version for netbeans.
try{
int rows=jTable1.getRowCount();
for(int row = 0; row<rows; row++)
{
Integer qty = (Integer)jTable1.getValueAt(row, 0);
Double unitprice = (Double) jTable1.getValueAt(row, 1);
String description = (String)jTable1.getValueAt(row, 2);
Double total = (Double)jTable1.getValueAt(row, 3);
String queryco = "Insert into invoice(qty,unitprice,description,total) values ('"+qty+"','"+unitprice+"','"+description+"','"+total+"')";
pst = conn.prepareStatement(queryco);
pst.execute();
}
JOptionPane.showMessageDialog(null, "Successfully Save");
}
catch(Exception e){
JOptionPane.showMessageDialog(this,e.getMessage());
}