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

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

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

Unable to query database correctly using JDBC

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

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

Insert Mulitple Row Data from Jtable into database

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

Is to iterate through a jTable and pass column values to an sql query in java

I have a jTable with 4 columns and 6 rows. i want to iterate thru the rows picking up the values of column index0 which is my ID column and passing it to a count sql query. i have written the below code which is not working because i haven't figured out how to pass the columns values after iterating through the table.
can someone please let me know what am doing wrong on my code please.
for (int row = 0; row > jTable2.getRowCount(); row++){
for (int col =0; col > jTable2.getColumnCount(); col ++)
try{
DefaultTableModel model = (DefaultTableModel)jTable2.getModel();
String selected = model.getValueAt(row, col+1).toString();
String sql = "select COUNT(COURSEBOOKED) from APP.BOOKCOURSE where COURSEBOOKED = '"+selected+"'";
try(Connection con = DriverManager.getConnection("jdbc:derby:MTD","herbert","elsie1*#");
PreparedStatement pst = con.prepareStatement(sql);) {
ResultSet rs = pst.executeQuery();
while(rs.next()){
String Sum = rs.getString("COUNT(COURSEBOOKED)");
System.out.println(Sum);
if (rs.wasNull()){
System.out.println("No record found");
}
}
}
catch(SQLException e){
}
}
catch(Exception e){
}
}
This is the final code that came up with after the changes.
String sql = "select COUNT(COURSEBOOKED) as count from APP.BOOKCOURSE where COURSEBOOKED =?";
try(Connection con = DriverManager.getConnection("jdbc:derby:MTD","herbert","elsie1*#");
PreparedStatement pst = con.prepareStatement(sql);){
for(int row = 0; row < jTable2.getRowCount(); row++){
DefaultTableModel model = (DefaultTableModel)jTable2.getModel();
String selected = model.getValueAt(row, 1).toString();
pst.setString(1, selected);
try(ResultSet rs = pst.executeQuery();){
while (rs.next()){
String Sum = rs.getString("count");
System.out.println(Sum);
}
}
}
}
catch(SQLException e){
JOptionPane.showMessageDialog(this, e);
}
Which brings me to my next question. AM not sure whether i should start a new thread for it or continue on this one. My challenge is that i now want to append an addition column to the existing 4 columns on the current jTable2 and display the values of the above query. to add a new column i have used this code,
TableColumn c = new TableColumn();
c.setHeaderValue("Training accomplished");
model.addColumn(c);
This adds the column but populates its with values from column index0. how do i get the new added column to be populated by the values held in Sum from the query above.
You should use something like below. Note that I haven't tested this code so far, so you might need to debug it. Also check the comments on your question.
String sql = "select COUNT(COURSEBOOKED) as count from APP.BOOKCOURSE where COURSEBOOKED = ?";
try(
Connection con = DriverManager.getConnection("jdbc:derby:MTD","herbert","elsie1*#");
PreparedStatement pst = con.prepareStatement(sql);){
for (int row = 0; row < jTable2.getRowCount(); row++){
DefaultTableModel model = (DefaultTableModel)jTable2.getModel();
String selected = model.getValueAt(row, 0).toString();
pst.setString(1, selected);
ResultSet rs = pst.executeQuery();
while(rs.next()){
String Sum = rs.getString("count");
System.out.println(Sum);
if (rs.wasNull()){
System.out.println("No record found");
}
}
}
}
catch(SQLException e){
}
catch(Exception e){
}

Categories

Resources