I am trying to update the current score in a table on Apache derby. If something already exists then I want it to update or replace the score with new one, and if nothing exists then I want it to insert.
I have written this so far and not sure what to use instead of REPLACE as that is giving me a SQL Error. The WHERE Statement is also giving me an error.
public void saveScore(int score) throws SQLException {
Statement statement = connection.createStatement();
String saveScore = ("REPLACE INTO USER_TABLE (USER_SCORE) VALUES (" + score + ") WHERE USER_TABLE.USER_NAME = '" + gameUsername + "'");
statement.executeUpdate(saveScore);
System.out.println("Score: " + score + " saved for " + gameUsername);
}
Derby doesn't have the REPLACE INTO statement from MySql: use MERGE instead.
See https://db.apache.org/derby/docs/10.13/ref/rrefsqljmerge.html
Related
I am making a program using Eclipse that allows the user to update the volume of chemicals everytime they’re restocked/used, which requires them to enter the ID of the chemical and the amount they would like to add/subtract. A query is then performed to search for the chemical's ID in the database, and its volume is updated accordingly.
However, I’m having difficulties getting the volume to update. I tried adapting MySQL’s UPDATE statement from this website to SET volume = volume + amount added, WHERE chemical ID = ID entered by the user; however, there appears to be some syntax errors in my code, more specifically at the UPDATE - SET - WHERE line:
public void IDEnter() {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:8889/StockControlSystem","root","root");
Statement stmt = con.createStatement();
String sql = "Select * from Chemicals where `Chemical ID` ='" + txtChemical_ID.getText()+"'";
ResultSet rs = stmt.executeQuery(sql);
if(rs.next()) {
stmt.executeUpdate("UPDATE Chemicals" + "SET `Volume` = rs.getInt(Volume) + Integer.parseInt(AmountAdded.getText()) WHERE `Chemical ID` in (txtChemical_ID.getText())");
}
else {
JOptionPane.showMessageDialog(null, "Invalid chemical ID");
txtChemical_ID.setText(null);
}
} catch(Exception exc) {
exc.printStackTrace();
}
}
Since I'm still new to MySQL, can someone help me correct this? Thank you so much for your help!
Your whole query is badly formatted. Change your code to this:
stmt.executeUpdate("UPDATE Chemicals SET Volume = " +
rs.getInt(Volume) + Integer.parseInt(AmountAdded.getText())
+ " WHERE Chemical_ID in (" + txtChemical_ID.getText() + ")");
You cannot use ' single quotes when defining Column names in queries. Single quotes are used for string values!
Still, this would not be the best way to do this. use PreparedStatement!
This way:
String updateString = "UPDATE Chemicals SET Volume = ? WHERE Chemical_ID in (?)"; // Creation of the prepared statement, the ? are used as placeholders for the values
PreparedStatement preparedStatement = con.prepareStatement(updateString);
preparedStatement.setInt(1, rs.getInt(Volume) + Integer.parseInt(AmountAdded.getText())); // Setting the first value
preparedStatement.setString(2, txtChemical_ID.getText()); // Setting the second. I am supposing that this txtChemical_ID textField has values seperated by commas, else this will not work!
preparedStatement.executeUpdate();
If you need to read more for PreparedStatement there are a lot of great resources out there. They also protect against SQL injections.
I think your problem might be with the "rs.getInt(Volume)"
Yours:
"UPDATE Chemicals" + "SET `Volume` = rs.getInt(Volume)
+ Integer.parseInt(AmountAdded.getText())
WHERE `Chemical ID` in (txtChemical_ID.getText())"
Can you try this:
"UPDATE Chemicals" + "SET `Volume` = " +
Integer.parseInt(AmountAdded.getText()) + "
WHERE `Chemical ID` in (" + (txtChemical_ID.getText()) +")"
ResultSet rs = stat.executeQuery("select * from donor where username = '" + username + "'");
String type = rs.getString("bloodtype");
System.out.println("the user's blood type is: " + type);
String Updatesentence = "update bank set " + type + " = " + type + " + 1 where name = '" + name + "'";
System.out.println(Updatesentence);
stat.executeUpdate(Updatesentence);
Guys I am trying to make an update to an SQL database with this code and although I am not getting an error somewhere the code does not work with the desired result. The
System.out.println(Updatesentence);
is not printed and the update is not performed. I know there probably is somewhat of a syntax error on my String declaration, but I cannot work it out.
You have this:
String Updatesentence = "update bank set " + type + " = " + type + " + 1 where name = '" + name + "'";
So if the user's blood type is AB...
update bank set AB = AB + 1 where name = 'JohnSmith'
And that obviously won't work. You need to indicate the column in the database you want to be updating.
One of the most important things you need to remember when writing SQL statements, is to separate the query literal from the query arguments. This allows protection from SQL Injection and also makes it possible for the DB to reuse the query with different arguments (and "hard parsing" / optimizing the query only once). The way you do this with JDBC, is through prepared statements:
try (PreparedStatement queryPS = myConnection.prepareStatement(
"select * from donor where username = ?");
PreparedStatement updatePS = myConnection.prepareStatement(
"update bank set bloodtype = ? where name = ?");) {
queryPS.setString(1, username);
ResultSet rs = queryPS.executeQuery();
if (rs.next()) {
String type = rs.getString("bloodtype");
System.out.println("the user's blood type is: " + type);
updatePS.setString(1, type);
updatePS.setString(2, username);
updatePS.executeUpdate();
}
} catch (SQLException e) {
// handle it
}
When you use prepared statements, you don't need to worry about concatenating the inputs into the query; they will be sanitized and injected automatically. If you're doing things the "wrong way", it's really easy to make a mistake when you construct the query piece by piece from different variables in your code, and this is exactly what happened with the misplaced type variable in your example.
Your update statement is wrong. It should be :
String Updatesentence = "update bank set bloodtype = " + type + " + 1 where name = '" + name + "'" ;
I'm coding some database transactions by using java. I'm sending a query using java. I think it has no problem with it. And if I send the query at prompt, it is working.
This method is updating book quantity.
private static void updateBquantity(int bqt, String bname) {
Connection con = makeConnection();
try {
Statement stmt = con.createStatement();
System.out.println(bqt + " " +bname);
//this part is making problem
stmt.executeUpdate("update books set bookquantity = bookquantity -" + bqt + "where bookname = '" + bname + "';");
System.out.println("<book quantity updated>");
} catch (SQLException e) {
System.out.println(e.getMessage());
System.exit(0);
}
stmt.executeUpdate("update books set bookquantity = bookquantity -" + bqt + "where 도서이름 = '" + bname + "';");
This part is making problem.
Other queries using this form is working.
The compiler says :
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'bookname = 'Davinci Code'' at line 1
Help me.
I'm confused with bookname = 'Davinci Code, where is bookname in your query? No matter what, in this query, you missed a blank before where, try this:
stmt.executeUpdate("update books set bookquantity = bookquantity -" + bqt + " where 도서이름 = '" + bname + "';");
I'm trying to update a table in my AccessDB and i'm having a weird problem.
The update executes without throwing any exceptions but the date value is wrong and
everytime i update a record the value always changes to "30/12/1899".
Same thing hapens when i'm trying to insert a new record.
In my DB the Date field is in ShortDate format.
Here is an example of my code:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
if (jList1.isSelectionEmpty()) {
JOptionPane.showMessageDialog(null, "You have not selected any computer!");
} else {
try {
String sql = "Update SYSTEMS set "
+ " CPU='" + cpuTextField.getText().trim()
+ "', MOBO='" + moboTextField.getText().trim()
+ "', RAM='" + ramTextField.getText().trim()
+ "', GPU='" + gpuTextField.getText().trim()
+ "', HDD='" + hddTextField.getText().trim()
+ "', PSU='" + psuTextField.getText().trim()
+ "', MONITOR='" + monitorTextField.getText().trim()
+ "', KEYBOARD='" + keyboardTextField.getText().trim()
+ "', MOUSE='" + mouseTextField.getText().trim()
+ "', OS='" + osTextField.getText().trim()
+ "', SOFTWARE='" + othersTextArea.getText().trim()
+ "', PURCHASE_DATE=" + df.format(jDateChooser1.getDate())
+ " where SYSTEM_ID='" + jList1.getSelectedValue().toString() + "'";
st = con.prepareStatement(sql);
st.executeUpdate();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
JOptionPane.showMessageDialog(null, "Updated");
}
}
In order to figure out what is going wrong, I made a button and when pressed i had
a Message showing the result of df.format(jDateChooser1.getDate()) and
it showed the correct date.
private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
JOptionPane.showMessageDialog(null, df.format(jDateChooser1.getDate()));
}
I'm using this component to get the date: JCalendar If that makes any difference.
I dont mind replacing it with a plain TextField, as long as the date is imported correctly.
When using select to retrieve the date from the DB everything goes well.
The problem only occurs when updating/inserting.
The problem likely has to do with the formatting of the SQL query; use a PreparedStatement instead of formatting it manually. Doing so will also decrease the likelihood of errors related to validating user input, including security issues such as SQL injection. For example:
String sql = "Update SYSTEMS set "
+ " CPU=?, MOBO=?, RAM=?"
+ //...
+ ", PURCHASE_DATE=?"
+ " where SYSTEM_ID=?";
PreparedStatement stmt = con.prepareStatement(sql);
int nextField = 1;
stmt.setString(nextField++, cpuTextField.getText().trim());
stmt.setString(nextField++, moboTextField.getText().trim());
stmt.setString(nextField++, ramTextField.getText().trim());
// ...
stmt.setDate(nextField++, jDateChooser1.getDate());
stmt.setString(nextField++, jList1.getSelectedValue().toString());
stmt.executeUpdate();
[Edit] Note that the PreparedStatement#setDate() method requires a java.sql.Date, so you may need to convert the date type returned by your date chooser into one of those, e.g.:
stmt.setDate(nextField++,
new java.sql.Date(jDateChooser1.getDate().getTime()));
Access requires dates to specified in format #MM/dd/yyyy# (including the hash marks). So if you add the # delimiters at the beginning and end of the date string, it should work. As maerics suggested, the best would be to use PreparedStatement, because the JDBC drive will handle converting Java Date to the format Access understands, without you needing to format the value.
Looks like your date format is different from what Access expects.
To get rid of it, use name parameters - as at http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html#supply_values_ps, rather than concatenating the SQL on your own.
I'm making a db call as follows:
String sqlAlert = "SELECT * FROM demotable where demo_no ='"
+rsDemo.getString("demo_no") + "'";
ResultSet rsAlert = db.GetSQL(sqlAlert);
if (rsAlert.next()) {
String newAlert = rsAlert.getString("cust3")+"1";
String newAlertSql = "UPDATE demotable SET cust3 = '" + newAlert + "' where demo_no='" + rsDemo.getString("demo_no") + "'";
System.out.println("Update alert msg: " + newAlertSql);
db.RunSQL(newAlertSql);
} else {
System.out.println("empty result. Demo_no = "+rsDemo.getString("demo_no"));
String sqlAlertinsert = "INSERT INTO demotable VALUES('" + rsDemo.getString("demo_no") + "','','','','','<unotes></unotes>')";
db.RunSQL(sqlAlertinsert);
System.out.println("insert demo done");
String sqlAlert2 = "SELECT * FROM demotable where demo_no ='"rsDemo.getString("demo_no") + "'";
ResultSet rsAlert2 = db.GetSQL(sqlAlert2);
if (rsAlert2.next()) {
String newAlert = rsAlert2.getString("cust3")+"1";
String newAlertSql = "UPDATE demotable SET cust3 = '" + newAlert+ "' where demo_no='" + rsDemo.getString("demo_no") + "'";
System.out.println("Update alert msg: " + newAlertSql);
db.RunSQL(newAlertSql);
}
rsAlert2.close();
}
rsAlert.close();
rs.close();
I am trying to insert rows into demographiccust if rsAlert returns an empty set and then access values from it. But my code returns this exception "Illegal operation on empty result set" around "if (rsAlert2.next()) { ". Why does it return an empty set even after inserting values into the table? Please help. Thank you.
It may be because of the open cursor. You must close your first Statement, prior trying the second. ResultSet is a connected thing, when you close the Statement it get closed too. I can't see the implementation of your db.RunSQL() and db.GetSQL() methods.
However, I am having the suggestion on how you should do it, in the first place. Here you go,
Update it without querying the database
Check how many rows updated. If none, then step 3, otherwise completed
Insert the record with the correct values in the first place. No need to update it after inserting.
Tips:
Try using PreparedStatement, instead
Try to stick with Java Naming Convention
Try using meaningful names, i.e. for example your method db.GetSQL() is not returning an SQL, but contrarily asking one, and in fact returning a ResultSet.
Never return a ResultSet. This may lead to bloated code and a lot of open cursors. Don't make the user of your method to close it. Close it yourself in your method where you are performing any database query, and return the result as a bean or a list of beans.
It's just a guess, but because you are interpolating rsDemo.getString("demo_no") directly into the SQL, you may be passing an SQL statement that isn't what you want. Try using the parameter binding api.