Mysql Java update column from jtextfield - java

How to update a field in my database from a JTextField using java?
My field in the data base: total
My field in java: add_quantity
I need to add the quantity to the total, using sql.
total = total + add_quantity
I tried this:
String value1 = jTextField5.getText();
PreparedStatement pst = cn.prepareStatement("UPDATE Capitales_totales SET capital_total = $capital_total + '"+value1+"';
What is the correct syntax for doing that?

Your question isn't very clear, datatype of the capital_total isn't provided. So, we'll assume that it's integer or numeric datatype.
MySQL syntax to add a value to the value that's already stored in a column, is something like this:
UPDATE mytable
SET mycol = mycol + 20
WHERE id = 1
If mycol contains a NULL value, then a NULL will be assigned. (An unknown value
plus 20 results in an unknown value.) If you want to handle a NULL value as if it were zero...
UPDATE mytable
SET mycol = IFNULL(mycol,0) + 20
WHERE id = 1
As far as how you do that in Java prepared statement, use a bind placeholder in place of the value in the SQL text, and then provide a value for the bind placeholder with the setString method.
String sql = "UPDATE mytable
SET mycol = IFNULL(mycol,0) + ?
WHERE id = 1";
PreparedStmt pst = cn.prepareStatement(sql);
pst.setString(1, value1);

Try using binds, e.g.
PreparedStatement pst = cn.prepareStatement("UPDATE Capitales_totales SET capital_total = capital_total + ?");
pst.setInt(1, Integer.parseInt(value1));
Note: Integer.parseInt() may throw RuntimeExpection

sample code snippet for the use-case:
PreparedStatement pst = cn.prepareStatement("Update Capitales_totales set capital_total =capital_total+?");
pst.setString(1, Integer.parseInt("int_string"));
OR
pst.setInt(1, 1001); //sample int 1001

Related

Prepared statement with set null in query doesn't return any record

I use prepared statements to read/write data in my DB (SQLite). In my table INVENTORY, there are records which have null value in the column paleta (the column is defined as VARCHAR in the table). I want to select these records and I tried:
sq = "SELECT * FROM INVENTORY WHERE paleta = ? AND product = ? AND lot = ?";
//...
stm = c.prepareStatement(sq);
stm.setNull(1, java.sql.Types.VARCHAR);
stm.setString(2, "theIdOftheProduct");
stm.setString(3, "theLotOftheProduct");
ResultSet rs = stm.executeQuery();
The above query doesn't return anything.. I removed the paleta = ? and I get the records I want.. How can I define the query like SELECT * FROM INVENTORY WHERE paleta is null etc.. using the query parameters?
What you are trying to do is equivalent to writing SELECT * FROM INVENTORY WHERE paleta = NULL ..., which doesn't work.
Since you are essentially searching for rows having a constant value in the paleta column (which happens to be NULL), you can eliminate the first query parameter and explicitly check for null:
sq = "SELECT * FROM INVENTORY WHERE paleta IS NULL AND product = ? AND lot = ?";
stm = c.prepareStatement(sq);
stm.setString(1, "theIdOftheProduct");
stm.setString(2, "theLotOftheProduct");
I found my answer in https://stackoverflow.com/a/4215618/1052284
You'll have to decide upon an unused value. I simply kept it at '' since I don't have empty values.
sq = "SELECT * FROM INVENTORY WHERE IFNULL(paleta, '') = ? AND product = ? AND lot = ?";
//...
stm = c.prepareStatement(sq);
stm.setString(1, ""); // '' for NULL, otherwise a specific value
stm.setString(2, "theIdOftheProduct");
stm.setString(3, "theLotOftheProduct");
But beware if you many queries, it's VERY slow. I clock in at about 4000 times slower, on average, than queries without IFNULL. ~50ms instead of microseconds.

Getting SQL error SQL State S1009

I'm trying to insert values into a table (inquiry) the first value is of type Date , and I'm getting an SQL error SQL State S1009. what is the proper way to convert the date , what am I doing wrong?
String sqlStatement = "INSERT INTO inquiry (INQUIRY_DATE,INQUIRY_NOTE,INQUIRER_ID,PROGRAM_ID,CLASS_ID,CORPORATE_ID)\n"
+ "VALUES (?,?,?,?);";
ps = con.prepareStatement(sqlStatement);
java.sql.Date sDate = new java.sql.Date(inquiry.getInquiryDate().getTime());
int parameterIndex = 1;
ps.setDate(parameterIndex, sDate);
ps.setString(parameterIndex++, inquiry.getInquiryNote());
ps.setInt(parameterIndex++, inquiry.getInquirer().getInquirerID());
ps.setInt(parameterIndex++, inquiry.getProgramID());
ps.setInt(parameterIndex++, inquiry.getClassProgramID());
ps.setInt(parameterIndex++, 1);
sqlStatement = "INSERT INTO inquiry (INQUIRY_DATE,INQUIRY_NOTE,INQUIRER_ID,PROGRAM_ID,CLASS_ID,CORPORATE_ID)\n"
+ "VALUES (?,?,?,?);";
The parameterized query doesn't have enough ?, you queried 6 columns with 2 ? missing, it should be VALUES (?,?,?,?,?,?); ? are used for holding the places for your setXXX() column values

PreparedStatement not working for substring_index?

I'm using this:
PreparedStatement preStatement = conn.prepareStatement("SELECT * FROM SomeTable WHERE attributeId = ? AND substring_index(substring_index(rowIdCombo,',',2),',',-1) = ?");
preStatement.setString(1, anAttributeID.toString());
preStatement.setString(2, locationID.toString());
Searching using the same query works fine on the MySQL terminal. It's only when using PreparedStatement in Java that it doesn't.
rowIdCombo is basically a string of numbers with comma separated values. Something like this: 23,56,64,3.
The result set returned is empty. How do I get this query to work?
Based on the output of
System.out.println(preStatement);
which was:
com.mysql.jdbc.PreparedStatement#223d2c72: SELECT * FROM mydb.SomeTable WHERE attributeId = '6' AND substring_index(substring_index(rowIdCombo,',',2),',',-1) = '1'
and as per your comment, that replacing = '1' with = 1 have solved the issue, to prevent the single quotes wrapping, set the value in the PreparedStatement as integer, use this:
preStatement.setInt(2, Integer.parseInt(locationID.toString()));

Inserting a value to a Foreign key using java and database

i need some solution from my foreign key in inserting a FK ID the problem is when i insert the ID, and the Payment it will insert first Customer_ID and the second is default to null value and on next column it will set to the inserted and the other one is null here's my code
pStmt2 = conn.prepareStatement("insert into Audittrail_tbl (Customer_ID) values ((Select Name_ID from Customer_tbl where FName ='"+txtFName.getText()+"' and LName = '"+txtLName.getText()+"'))");
pStmt2 = conn.prepareStatement("insert into Audittrail_tbl (Payment) values ('"+txtPayment.getText()+"')");
pStmt2.executeUpdate();
Your code should be:
String sql = "insert into Audittrail_tbl (Customer_ID, Payment)" +
" select Name_ID, ?" +
" from Customer_tbl" +
" where FName = ?" +
" and LName = ?";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, txtPayment.getText());
stmt.setString(2, txtFName.getText());
stmt.setString(3, txtLName.getText());
stmt.executeUpdate();
}
Or better yet, if Payment is an amount column:
// Using BigDecimal
stmt.setBigDecimal(1, new BigDecimal(txtPayment.getText()));
// Using Double
stmt.setDouble(1, Double.parseDouble(txtPayment.getText()));
Since that will parse the text to number in Java code, where you can better handle parse errors.
Note: Using insert-from-select, instead of insert-values with a subquery, will allow you to select multiple columns from Customer_tbl if needed.
You're doing two inserts, which creates two records. if you want to update the record created by the first query, you need to UPDATE for the second query instead.
And why use two queries? Why not
pStmt2 = conn.prepareStatement("
insert into Audittrail_tbl (Customer_ID, Payment)
values (
(Select Name_ID from Customer_tbl where FName ='"+txtFName.getText()+"' and LName = '"+txtLName.getText()+"'),
'"+txtPayment.getText()+"')");)");
Of course, that won't work as-is (I'm too lazy to check quote/bracket matching), but should give you the general idea.

Update table field value to null programmatically

It is well known that how to set the field value to null by a simple query like -
UPDATE your_table
SET your_column = NULL
WHERE id = 1;
But pro-grammatically, which one is correct way to update the field value to null -
db.execSQL("UPDATE your_table SET your_column='" + null + "WHERE id='" + myid + "'");
OR
db.execSQL("UPDATE your_table SET your_column= NULL WHERE id='" + myid + "'");
Thanks
I would go with PreparedStatement.
String query="UPDATE your_table SET your_column= ? WHERE id=?");
PreparedStatement stmnt = conn.prepareStatement(query);
if(colyouAretryingtopass == null){]
stmnt.setNull(1, Types.VARCHAR);
}
The correct way is to use bind variables, depending on the framework you are using this is done in different ways.
You query should be something like follows;
String query = "UPDATE your_table SET your_column = null WHERE id = ?";
executeQuery(query, id);
Where executeQuery(String query, Object... args) is the the DB access method of your choice.
If you don't use bind variables you are;
a) Vunerable to SQL injection.
b) Losing performance by not utilising query cache on the database.

Categories