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());
}
Related
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 (...);
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());
}
}
When I am typing in jtable row I need to get suggestions to that table rows(filtered) from mysql data base and select from it (like Invoice generating as picture )I need to develop as below picture and here is the code I coded so far
jdbc j = new jdbc();
DefaultTableModel dt = (DefaultTableModel) tab_reta_in.getModel();
int row = tab_reta_in.getSelectedRow();
int col = tab_reta_in.getSelectedColumn();
Data_feild = (String) tab_reta_in.getValueAt(row, col);
int Def_r = row;
if (col == 0) {
try {
ResultSet rs = j.GetData("select * from invoice_retails where name like '" + Data_feild + "%' ");
while (rs.next()) {
String col0 = rs.getString("medi_id");
String col1 = rs.getString("name");
String col2 = rs.getString("prize");
Object[] rows = {col0, col1, col2};
dt.addRow(rows);
}
} catch (Exception ex) {
System.out.println(ex);
}
I fixed the problem I had with my rs, and now here's my code:
while (rs.next()) {
for (int i = 1; i <= columnCount; i++) {
String resultado = "";
resultado = rs.getString(i);
columnValue += resultado;
}
columnValue += "), (";
}
String sub = columnValue.substring(0, columnValue.length() - 3);
jTextPane2.setText(jTextPane2.getText() + sub);
sub = "";
columnValue = "";
jTextField1.setText("");
and the Result I get is this:
(id_tlf, cod_area)
(1+58), (2+104), (3+100)
How should I edit my code so that it looks like this:
(id_tlf, cod_area)
(1, +58), (2, +104), (3, +100)
If you see, I want to add a comma after the first rs and not on the 2nd one
Hi I have an arraylist of strings, I want to show the content of the arraylist on JLabel separated by a space or comma. But it shows me only one String, the last one.
public void ShowMovie(int idMovie) throws SQLException, IOException {
int ID = idMovie;
String IDMOVIE = Integer.toString(ID);
IDMovieLabel.setText(IDMOVIE);
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException ex) {
Logger.getLogger(Cover.class.getName()).log(Level.SEVERE, null, ex);
}
con = DriverManager.getConnection("jdbc:mysql://localhost/whichmovie", "Asis", "dekrayat24");
String sql = "SELECT Title,Year,Country,recomendacion,Cover,Rating,NameDirec,Name FROM movie "
+ "Inner join direction on (movie.idMovie=direction.idMovie5)"
+ "Inner join director on (direction.idDirector=director.idDirector)"
+ "Inner join cast on (movie.idMovie=cast.idMovie4)"
+ "Inner join actor on (cast.idActor=actor.idActor)"
+ "where idMovie= '" + ID + "'";
st = con.prepareStatement(sql);
rs = st.executeQuery(sql);
while (rs.next()) {
String titulo = rs.getString(1);
int añoInt = rs.getInt(2);
String año = Integer.toString(añoInt);
byte[] imagedataCover = rs.getBytes("Country");
byte[] imagedataCover1 = rs.getBytes("Cover");
format = new ImageIcon(imagedataCover);
format2 = new ImageIcon(imagedataCover1);
TituloLabel.setText(titulo);
AñoLabel.setText(año);
CountryLabel.setIcon(format);
DirectorLabel.setText(rs.getString(7));
int Recomend = rs.getInt(4);
String Recom = Integer.toString(Recomend);
RecommendLabel.setText(Recom);
int Rating = rs.getInt(6);
String Rat = Integer.toString(Rating);
RatingLabel.setText(Rat);
starRater1.setSelection(Rating);
starRater1.setEnabled(false);
Image imgEscalada = format2.getImage().getScaledInstance(CoverLabel.getWidth(),
CoverLabel.getHeight(), Image.SCALE_SMOOTH);
Icon iconoEscalado = new ImageIcon(imgEscalada);
CoverLabel.setIcon(iconoEscalado);
ArrayList<String> actors = new ArrayList<>();
actors.add(rs.getString(8));
System.out.println(actors);// Here i can see i get 9 actors.
StringBuilder sb = new StringBuilder();
boolean first = true;
for (String s : actors) {
if (!first) {
sb.append(' ');
}
sb.append(s);
first = false;
}
CastLabel1.setText(sb.toString());
}
rs.close();
st.close();
con.close();
}
Any help ?
Edit:unfortunately no solution has helped me, maybe I'm doing something wrong in the method, I post the full method.
String text = "";
for(int i = 0; i < actors.size(); i++){
text = text + actors.get(i);
if(i < actors.size() - 2){
text = text + ", ";
}
}
CastLabel1.setText(text);
The problem is you are resetting the label for each step in the for loop, and not creating a cumulative result. See below:
StringBuilder buf = new StringBuilder();
for(int i = 0; i < actors.size(); i++){
buf.append(actors.get(i));
if(i < actors.size() -1){
buf.append(" ");
}
}
CastLabel1.setText(buf.toString())
You should build the string you want to show first then set it to the text of the label:
StringBuilder sb = new StringBuilder();
boolean first = true;
for (String s : actors) {
if (!first)
sb.append(' ');
sb.append(s);
first = false;
}
CastLabel1.setText(sb.toString());
What you're currently doing is changing the entire label text during each iteration, so the final text is that of the last element in the list.