Cannot update multiple times using for loop - java

I have a form that borrows stocks from branchA to branchB. The user can input multiple products and I do this by having a text area split it with (","), and place in it an array. After submitting my form, I insert it in a table and then update the stocks from another table. Here is my code (which I actually placed in a JSP file instead of a normal Java class):
try {
for (int iCtr=0; iCtr<idsplit.length; iCtr++) {
sInsertQuery = "INSERT INTO PULLOUT_REPORTS (control_number, dateofpullout, item_des, item_size, item_qty, pullout_from, pullout_to) values ('"+cn+"','"+po+"','"+idsplit[iCtr]+"','"+issplit[iCtr]+"','"+qtsplit[iCtr]+"','"+fr+"','"+to+"')";
pInsertPullout = conn.prepareStatement(sInsertQuery);
pInsertPullout.executeUpdate();
if (fr.equals("Antipolo") && to.equals("Binangonan")) {
sUpdateRecord = "UPDATE maintable SET antip_qty = antip_qty - ? WHERE item_code = ? AND item_size = ?";
pUpdateFrom = conn.prepareStatement(sUpdateRecord);
pUpdateFrom.setString(1,qtsplit[iCtr]);
pUpdateFrom.setString(2,idsplit[iCtr]);
pUpdateFrom.setString(3,issplit[iCtr]);
pUpdateFrom.addBatch();
pUpdateFrom.executeBatch();
sUpdateRecord1 = "UPDATE maintable SET binang_qty = binang_qty + ? WHERE item_code = ? AND item_size = ?";
pUpdateTo = conn.prepareStatement(sUpdateRecord1);
pUpdateTo.setString(1,qtsplit[iCtr]);
pUpdateTo.setString(2,idsplit[iCtr]);
pUpdateTo.setString(3,issplit[iCtr]);
pUpdateTo.addBatch();
pUpdateTo.executeBatch();
} }
}
catch (Exception e) {
response.sendRedirect("error.jsp");
}
The first query successfully inserts multiple rows in the table but my second query only updates the first index from the array. I don't know what I could be doing wrong since they're both inside the same loop.
Any help please?
UPDATE: I did this .addBatch and .executeBatch and it work a while, now it doesn't work again. It only updates the first index.

Try something like this snippet (i might ve messed up with types of your variables, because I guessed them.
try {
sInsertQuery = "INSERT INTO PULLOUT_REPORTS " +
"(control_number, dateofpullout, item_des, item_size, item_qty, pullout_from, pullout_to)" +
" values " +
"(?,?,?,?,?,?,?)";
pInsertPullout = conn.prepareStatement(sInsertQuery);
sUpdateRecord = "UPDATE maintable SET antip_qty = antip_qty - ? WHERE item_code = ? AND item_size = ?";
pUpdateFrom = conn.prepareStatement(sUpdateRecord);
sUpdateRecord1 = "UPDATE maintable SET binang_qty = binang_qty + ? WHERE item_code = ? AND item_size = ?";
pUpdateTo = conn.prepareStatement(sUpdateRecord1);
for (int iCtr=0; iCtr<idsplit.length; iCtr++) {
pInsertPullout.setLong(1, cn);
pInsertPullout.setLong(2, po);
pInsertPullout.setString(3, idsplit[iCtr]);
pInsertPullout.setString(4, issplit[iCtr]);
pInsertPullout.setString(5, qtsplit[iCtr]);
pInsertPullout.setString(6, fr);
pInsertPullout.setString(7, to);
pInsertPullout.executeUpdate();
pInsertPullout.clearParameters();
if (fr.equals("Antipolo") && to.equals("Binangonan")) {
pUpdateFrom.setString(1,qtsplit[iCtr]);
pUpdateFrom.setString(2,idsplit[iCtr]);
pUpdateFrom.setString(3,issplit[iCtr]);
pUpdateFrom.addBatch();
pUpdateTo.setString(1,qtsplit[iCtr]);
pUpdateTo.setString(2,idsplit[iCtr]);
pUpdateTo.setString(3,issplit[iCtr]);
pUpdateTo.addBatch();
}
}
pUpdateFrom.executeBatch();
pUpdateTo.executeBatch();
}
catch (Exception e) {
response.sendRedirect("error.jsp");
}
and don't forget to cleanup resources afterwards. Close statements and connection in finally{} clause.

Related

Varying content of an SQL update statement in java

I need to write an update function where its content is different based on what parameters are passed, e.g. if I have updateBook(int id, String title, String author, int pages), I have to do something like:
String sql;
if((!title.equals("null"))&&(!author.equals("null"))&&(pages>0)))
sql = "UPDATE book SET title='"+title+"', author='"+author+"', pages="+pages;
else if(((!title.equals("null"))&&(!author.equals("null")))
sql = "UPDATE book SET title='"+title+"', author='"+author+"'";
else if(((!title.equals("null"))&&(pages>0)))
sql = "UPDATE book SET title='"+title+"', pages="+pages;
... //and so on
sql = sql + " WHERE bookid="+id+";";
The more fields I have in my table, the more checks I have to do, which is uncomfortable, and requires me to write a lot of code.
Also, doing something like:
sql = "UPDATE book SET ";
if(!title.equals("null"))
sql = sql +"title='"+title+"',";
if(!author.equals("null"))
sql = sql+"author='"+author+"',";
if(pages>0)
sql = sql+"pages="+pages";
sql = sql + ";";
can't work since the unwanted commas cause statement errors.
You can see as well that if I have something like 6, 7, 8 etc field the checks start to get too many, and I can't also do more separated update statements as if something goes wrong I would need to rollback any query that has been done in that function.
Is there any way round to get a custom update statement having to write few code?
Firstly, use a PreparedStatement.
I would do it something like the following.
List<Object> params = new ArrayList<>();
StringBuilder sql = new StringBuilder();
if(!title.equals("null")) {
sql.append("title = ?");
params.add(title);
}
if(!author.equals("null")) {
if (sql.length() > 0) {
sql.append(", ");
}
sql.append("author = ?");
params.add(author);
}
if(pages>0) {
if (sql.length() > 0) {
sql.append(", ");
}
sql.append("pages = ?");
params.add(pages);
}
if (sql.length() > 0) {
sql.insert(0, "UPDATE book SET ");
sql.append(" WHERE bookid=?");
java.sql.Connection conn = // however you obtain it
java.sql.PreparedStatement ps = conn.prepareStatement(sql.toString());
for (int i = 0; i < params.size(); i++) {
ps.setObject(i + 1, params.get(i));
}
ps.executeUpdate();
}

How can i change Only one field value in MySQL?

I have a phonebook project I'm trying to make for school.
I want to be able to change a value of a certain field.
I print the field that are changeable.
before i had PRIMARY KEY it changed everyone for example if i changed the name, it would change everyone that is on the list name.
Now I tried to catch a specific one with a id as primary key and it throws this exception:
Parameter index out of range (2 > number of parameters, which is 1).
(this code now works if someone will see it in the future :)
I incremented the contactNum in the editConatct() to match it with the id field in my MySQL data base )
my edit code:
protected void editContawct(){
System.out.print("Which One You Want To Edit: ");
ArrayList<String> fields = editContactHelper();
ArrayList<Person> people = checkMoreThanOne();
int contactNum = menu(people);
int option = menu(fields);
System.out.println("Please Enter The Changes");
String changes = MyUtills.readStringFromUser();
String sql = "UPDATE " + DB_NAME + " SET " + fields.get(option) + " = ? WHERE ID = ?";
try {
statement = db.prepareStatement(sql);
statement.setString(1, changes);
statement.setInt(2,contactNum + 1); //contactNum `incremented to match 'id' field in my MySQL.`
statement.executeUpdate();
System.out.println("worked ?");
} catch (SQLException e) {
e.printStackTrace();
}
}
//todo add a param that accepts a String that is the data base name.
private ArrayList<String> editContactHelper(){ // should accept data base name
ArrayList<String> fieldsName = new ArrayList<>();
//todo switch the constant to the accepted argument (data base name). so if someone else wants to use this method :)
String sql = "SELECT * FROM " + DB_NAME; // should be databaseName;
try {
ResultSet resultSet = db.prepareStatement(sql).executeQuery();
ResultSetMetaData meta = resultSet.getMetaData();
for (int i = 1; i <= meta.getColumnCount(); i++) {
if(meta.getColumnName(i).equals("id")){
continue;
}
fieldsName.add(meta.getColumnName(i));
}
System.out.println("it worked Homie");
return fieldsName;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
Each ? is your query should relate to one parameter
But you have a mismatch
statement.setString(1, changes);
statement.setInt(2,contactNum);
as you only have one ?

java load values from database into comboBox

Hi my aim is to load combobox with vaules from a database the code below works fine with one issue i get two of the first item so what must i do to prevent this
public void loadCombos() {
try {
try {
String cs = "jdbc:mysql://localhost:3307/booksalvation6";
String user = "root";
String password = "letmein";
jComboBox2.removeAllItems();// make sure old data gone
PreparedStatement pstpost;
ResultSet rspost;
conCombos = DriverManager.getConnection(cs, user, password);
for (int i = 1; i < 11; i++) {
String querypost = "select * from post "
+ "WHERE postage_id =" + i;
// load postage selections
pstpost = conCombos.prepareStatement(querypost);
rspost = pstpost.executeQuery();
while (rspost.next()) {
String Mypost = rspost.getString(6);
jComboBox2.addItem(Mypost);
}
}
} catch (SQLException ex) {
Logger.getLogger(BasicFrame.class.getName()).log(Level.SEVERE, null, ex);
}
conCombos.close();
} catch (SQLException ex) {
Logger.getLogger(BasicFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
You are using PreparedStatement but not in proper way.
Since you are looking only for one column to fetch all the column values which have postage_id between 1 to 10.
You can achieve it in single query:
select unique(combo_value_column_name) from post
where postage_id>=? and postage_id<=?
set the parameter via calling PreparedStatement#setInt(index,value) set it 1 and 10.
Just fetch single column and only unique values.
It's better explained under Java Tutorial on Using Prepared Statements
Instead of calling JComboBox#addItem() first prepare the whole list then finally set it once.
Read more...
Final Note: Follow Java Naming Convention.

ResultSet returns only last row into JTable

I have done enough searches to solve my problem which i have done partly but there's this one bug that keeps disturbing me.I am trying to fetch data from a database based on a condition.I have a table 'user_branch' with a foreign key column branchID which is supposed to fetch the coresponding branchNames in another table 'branches' and I am supposed to display the results into a JTable.When i do System.out.println i get all my results but it returns only the last row when i display in a JTable(branchJTable).This is the code i am using
int row = user2BAssignedJTable.getSelectedRow();
assignUserID.setText(user2BAssignedJTable.getModel().getValueAt(row, 0).toString());
user2BAssignedField.setText(user2BAssignedJTable.getModel().getValueAt(row, 1).toString());
try {
String userBrQry = "SELECT branchID FROM user_branch WHERE userID IN(?) ";
String brQ = "SELECT branchName FROM branches WHERE branchID IN(%s) ";
pstmt = con.prepareStatement(userBrQry);
pstmt.setString(1, assignUserID.getText());
results = pstmt.executeQuery();
results.last();
int nRows = results.getRow();
results.beforeFirst();
while (results.next()) {
String branchIDS = results.getString("branchID");
StringBuilder builder = new StringBuilder();
for (int i = 0; i < nRows; i++) {
builder.append("?");
if (i + 1 < nRows) {
builder.append(",");
}
}
brQ = String.format(brQ, builder.toString());
PreparedStatement ps = con.prepareStatement(brQ);
for (int i = 0; i < nRows; i++) {
ps.setString(i + 1, branchIDS);
}
ResultSet rs = ps.executeQuery();
//branchJTable.setModel(DbUtils.resultSetToTableModel(rs));
javax.swing.table.DefaultTableModel model = new javax.swing.table.DefaultTableModel();
model.setColumnIdentifiers(new String[]{"Branch Name"});
branchJTable.setModel(model);
while (rs.next()) {
String branchname = rs.getString("branchName");
model.addRow(new Object[]{branchname});
}
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
Forget about the first 3 rows as it is a another JTable event i use to get the userID to use as a condition for getting a particular user's branches assigned to him.
The branches assigned to a user is dynamic hence using StringBuilder.
I am supposed to display the results into another JTable called branchJTable which only displays the last row.Any HELP would be appreciated!
From your question, I think you should declare the JTable
javax.swing.table.DefaultTableModel model = new javax.swing.table.DefaultTableModel();
model.setColumnIdentifiers(new String[]{"Branch Name"});
branchJTable.setModel(model);
before your first loop -
i.e. before while (results.next()) { in your code.
Otherwise in loop, for each loop execution,
the JTable Model is initialising and you are getting the last inserted row in Jtable.

Oracle UPDATE command with multiple conditions in Java

I'm having issues with the Java code below. It is supposed to update certain records in a table where the ID is given, and where the STATUS column is 'good' (this is only one row at any given time). However, when I run the code below, it seems to be ignoring the AND STATUS = 'good' part, and updating all NUMRECS wherever the ID matches.
static void insertNumRecs()
{
PreparedStatement insert = null;
try
{
String insertNumRecsCommand = "UPDATE FILESTATUS SET NUMRECS = ? " +
"WHERE ID = ? AND STATUS = 'good'";
insert = Main.con.prepareStatement(insertNumRecsCommand);
insert.setInt(1, Main.numRecs);
insert.setString(2, Main.docID);
insert.executeUpdate();
}
catch (Exception ex) {ex.printStackTrace();}
finally {close(null, insert);}
}
I've tried searching for this everywhere, but I couldn't find any answers. When I run the command directly from the database, it works fine, which confuses me even more.
Thanks in advance.
Try to write
"WHERE ID = ? AND STATUS = ?"
and use
insert.setString(3, "good");
This doesn't explain the problem, but I'd wonder why you don't do this:
static void insertNumRecs()
{
PreparedStatement insert = null;
try
{
String insertNumRecsCommand = "UPDATE FILESTATUS SET NUMRECS = ? " +
"WHERE ID = ? AND STATUS = ?";
insert = Main.con.prepareStatement(insertNumRecsCommand);
insert.setInt(1, Main.numRecs);
insert.setString(2, Main.docID);
insert.setString(3, "good");
insert.executeUpdate();
}
catch (Exception ex) {ex.printStackTrace();}
finally {close(null, insert);}
}
Can't see your data, so I can't tell if it's a case issue ("GOOD" != "good")
Sure you're connecting to the database you think you are? If the connection string points to one database, and you run your test against another, that would explain why you don't see the change.

Categories