I'm trying to get my JSpinners value to add to the column in my database,
why is my variable query2 working when I put it in db.update() but not query? What do I need to change?
try {
int points = (int) antalPoäng.getValue();
String query = "UPDATE ELEVHEM SET HUSPOANG = HUSPOANG" + points + "WHERE ELEVHEMSNAMN ='Gryffindor'";
String query2 = "UPDATE ELEVHEM SET HUSPOANG = HUSPOANG +1 WHERE ELEVHEMSNAMN ='Gryffindor'";
if (namnElevhem.getSelectedItem().equals("Gryffindor")) {
db.update(query);
JOptionPane.showMessageDialog(null,"The points has been added")
}
}
catch(InfException e) {
}
I suspect that in your first query you want to increment the HUSPOANG column by some amount. We could try to just correct your concatenated query string, but it would be much better to use a prepared statement here:
String sql = "UPDATE ELEVHEM SET HUSPOANG = HUSPOANG + ? WHERE ELEVHEMSNAMN = 'Gryffindor'";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, points);
ps.executeUpdate();
If you want to continue with your current approach, then you would need to fix your query string:
String query = "UPDATE ELEVHEM SET HUSPOANG = HUSPOANG + " + points +
" WHERE ELEVHEMSNAMN = 'Gryffindor'";
You were missing some needed spaces, but again it would be preferable to use a prepared statement, which it makes it easy to avoid such formatting problems.
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()) +")"
I have been struggling with an SQL Delete query. I want it to delete a row, Where 2 conditions are met. The error I am getting says my SQL Syntax is wrong near the end at the last ')'.
String sql = "DELETE FROM course
WHERE (username_entry = " + username +
" AND course_name = " + courseToDelete.toUpperCase() + ")";
My variables have the right values and the data in the database corresponds perfectly.
Here is an example of what your raw query might look like:
DELETE
FROM course
WHERE username_entry = tim AND course_name = chemistry;
Of course, this is not valid SQL, because you are comparing text columns against what will be perceived as other columns called tim and chemistry. You really want the above query to look like this:
DELETE
FROM course
WHERE username_entry = 'tim' AND course_name = 'chemistry';
In other words, you need to compare against properly escaped string literals. But in practice, the best thing to do is to use prepared statements, which handle the formatting automatically:
String sql = "DELETE FROM course WHERE username_entry = ? AND course_name = ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, username);
ps.setString(2, courseToDelete.toUpperCase());
ps.executeUpdate();
You need to encapsulate string values into quotes
String sql = "DELETE FROM course
WHERE (username_entry = '" + username +
"' AND course_name = '" + courseToDelete.toUpperCase() + "')";
But better way is to use prepared statements as they do automatical escape
Did you try to remove the braces after the Where clause.
The query would look like below after the change:
String sql = "DELETE FROM course
WHERE username_entry = '" + username +
"' AND course_name = '" + courseToDelete.toUpperCase()+"'";
You don't have to use any open / close paranthesis for the query as such!
As suggested in the other answers, you don't really need to use the injection of variables but instead, use the PreparedStatement
String sql = "DELETE FROM course
WHERE username_entry = '" + username +
"' AND course_name = '" + courseToDelete +"'";
Hope this helps!
Currently, I am using for loop, which is unacceptably slow when orgList has thousands of elements inside:
String sql = "SELECT xua.XUAID, xua.XUA01, xua.XUA02 "
+ "FROM dbo.XDSysUseArea xua "
+ "WHERE xua.XUA03=?";
conn = ds.getConnection();
ps = conn.prepareStatement(sql);
for(HotelSource org : orgList) {
ps.setString(1, org.getPrimaryKey());
rs = ps.executeQuery();
while (rs.next()) {
// do sth
}
}
What is the right way to do the SELECT?
You should use SQL IN, for example:
SELECT ... FROM ... WHERE xua.XUA03 IN (x, y, z, ...)
You can still parameterise your query, but you need to generate the correct number of ? in the statement. So some psuedocode here because I don't do Java:
String params = "?, ?, ?, ?"; //you will have to generate enough of these yourself
//This is an exercise for you!
String sql = "SELECT xua.XUAID, xua.XUA01, xua.XUA02 "
+ "FROM dbo.XDSysUseArea xua "
+ "WHERE xua.XUA03 IN (" + params + ")";
conn = ds.getConnection();
ps = conn.prepareStatement(sql);
int index = 1;
for(HotelSource org : orgList) {
ps.setString(index, org.getPrimaryKey());
// ^^^^^ use index here
index++;
}
rs = ps.executeQuery();
while (rs.next()) {
// do sth
}
Note: The downside of this is that you mention you have thousands of entries in orgList which makes it really bad practice to use this method. In fact, SQL Server will not allow you to use more than a couple of thousand parameters.
Use IN operator no need to hit the query for each value
SELECT xua.XUAID, xua.XUA01, xua.XUA02
FROM dbo.XDSysUseArea xua
WHERE xua.XUA03 in (val1,val2,val3,..) -- pass the list here
Store org.getprimarkey() in a arraylist List<Integer> past it to where clause using in operator
SELECT xua.XUAID, xua.XUA01, xua.XUA02 "
+ "FROM dbo.XDSysUseArea xua "
+ "WHERE xua.XUA03 IN (mylist);
NOTE: replace [ ] in list using replaceall method.
You can use operator IN for this purpose. Example,
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);
Im trying to add the number 1 to a certain field. How could i manage to do that? Ive tried it but i can never get it to add 1. My ms access table column is set to Number not text.
if (s2.equals(box1Text)) {
if (s3.equals(box2Text)) {
if (s5.equals(currentWinner)) {
String sql = "UPDATE Table2 "+ "SET Score = ? " + "WHERE Better = '" + s1+"'";
PreparedStatement stmt = con.prepareStatement(sql);
//points made here
if (s4.equals(betScore)) {
stmt.setString(1, "+1");//how could i add 1 to the field?
stmt.executeUpdate();
} else {
}
First you do something that is regarded as bad practice : you construct your query by adding the value of a parameter in the string.
String sql = "UPDATE... >+ s1 +<..."
Please nether do that (what is between > and <) when programming seriouly, but allways use ? to pass values.
Second, SQL can do the job for you :
String sql = "UPDATE Table2 SET Score = Score + 1 WHERE Better = ?";
PreparedStatement stmt = con.prepareStatement(sql);
stmt.setString(1, s1);
stmt.executeUpdate();
(try, catch, tests and other details omitted for brevity)
I know how to 'SET' it, but how can I add to it? Such as...
// Add 1 minute to the current 'time' object
try {
Connection con = DriverManager.getConnection(url, user, password);
String sql = "UPDATE Table "
+ "SET 'Time Field' = 'Time Field' + ? "
+ "WHERE 'User Column' = 'Random Name'";
PreparedStatement statement = con.prepareStatement(sql);
statement.setTime(0, new Time(60000));
} catch (SQLException e) {
e.printStackTrace();
}
I'm sure I have to use the "ADDITEM(expr1,expr2)" function, but how exactly would I do so? I feel like it's not as easy as just typing it into my String.
You shouldn't pass in a Java date/time: you should use a SQL time/date literal, or a MySQL time/date function. Either way, you no longer need a "time" variable in your prepared statement:
// EXAMPLE: add 2 hours to current time
String sql =
"UPDATE Table " +
"SET 'Time Field' = 'Time Field' + DATE_ADD(NOW(), INTERVAL 2 HOUR) " +
"WHERE 'User Column' = 'Random Name'";
Here are the available MySql date/time functions:
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
Use PreparedStatement class. The documantation is here:
http://docs.oracle.com/javase/6/docs/api/java/sql/PreparedStatement.html
Use ADDTIME() function as below:
String sql = "UPDATE Table "
+ "SET 'Time Field' = ADDTIME('Time Field', ?) "
+ "WHERE 'User Column' = 'Random Name'";
Then set the param value with desired value.