Insert Mulitple Row Data from Jtable into database - java

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());
}

Related

Is there a way on how to get the last inserted id that has prefix?

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);
}
}

How to fix the error on java.lang.ArrayIndexOutOfBoundsException: 4 >= 4

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());
}
}

how to insert jtable only one column data into DB mysql?

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);
}
}

How to insert many rows data of table into DB?

This is my code and i want two rows data into my database but when i proceed only last row or second rows data set into my database table :
try{
int rows=tblCO2.getRowCount();
for(int row = 0; row<rows; row++)
{
System.out.println(row);
String itemcode = (String)tblCO2.getValueAt(row, 0);
String lotno = (String)tblCO2.getValueAt(row, 1);
String stackno = (String)tblCO2.getValueAt(row, 2);
String grade = (String)tblCO2.getValueAt(row, 3);
String ctns = (String)tblCO2.getValueAt(row, 4);
try
{
Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
conn = DriverManager.getConnection("jdbc:derby://localhost:1527/demo","user","pw");
conn.setAutoCommit(false);
String queryco = "Insert into alicreative.pur(itemcode,lotno,stackno,grade,ctns) values (?,?,?,?,?)";
pst = conn.prepareStatement(queryco);
pst.setString(1, itemcode);
pst.setString(2, lotno);
pst.setString(3, stackno);
pst.setString(4, grade);
pst.setString(5, ctns);
pst.addBatch();
}
catch(ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException e)
{
JOptionPane.showMessageDialog(this,e.getMessage());
}
}
pst.executeBatch();
conn.commit();
}
catch( HeadlessException | SQLException e){
JOptionPane.showMessageDialog(this,e.getMessage());
}
So tell me solution for save two rows of data in one action.
You are creating a new Connection object for each row. Why ?
(As a consequence, you'll also have as many distinct PreparedStatement objects as you have rows. How many and which one will actually execute after the end of your loop ?)
Initialize your PreparedStatement (and create your connection) before your loop, because as it is, you are creating a new one at each iteration, and populating it with one batch.
Finally you end up executing only the last PreparedStatement (which contains only the batch for the last row) .
try{
int rows=tblCO2.getRowCount();
Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
conn = DriverManager.getConnection("jdbc:derby://localhost:1527/demo","user","pw");
conn.setAutoCommit(false);
String queryco = "Insert into alicreative.pur(itemcode,lotno,stackno,grade,ctns) values (?,?,?,?,?)";
PreparedStatement pst = conn.prepareStatement(queryco);
for(int row = 0; row<rows; row++)
{
System.out.println(row);
String itemcode = (String)tblCO2.getValueAt(row, 0);
String lotno = (String)tblCO2.getValueAt(row, 1);
String stackno = (String)tblCO2.getValueAt(row, 2);
String grade = (String)tblCO2.getValueAt(row, 3);
String ctns = (String)tblCO2.getValueAt(row, 4);
try
{
pst.setString(1, itemcode);
pst.setString(2, lotno);
pst.setString(3, stackno);
pst.setString(4, grade);
pst.setString(5, ctns);
pst.addBatch();
}
catch(ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException e)
{
JOptionPane.showMessageDialog(this,e.getMessage());
}
}
pst.executeBatch();
conn.commit();
}
catch( HeadlessException | SQLException e){
JOptionPane.showMessageDialog(this,e.getMessage());
}

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