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)
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'm working in one quiz game. There is question maker window. Which works good for saving question. But when want update one of text Field and press save, than error is happening. something is wrong with syntax?!
void insertCell(String tableNamer, String column, String value, int id) throws ClassNotFoundException, SQLException{
Class.forName("org.h2.Driver");
Connection conn = DriverManager.getConnection("jdbc:h2:file:C:/Users/Juris Puneiko/IdeaProjects/for_my_testings/src/sample/DB/Questions/For_Private/Easy", "Juris", "1");
PreparedStatement ps = conn.prepareStatement("UPDATE ? SET ? = ? where ID = ?");
ps.setString(1, tableNamer);
ps.setString(2, column);
ps.setString(3, value);
ps.setInt(4, id);
ps.executeUpdate();
ps.close();
conn.close();
}
org.h2.jdbc.JdbcSQLException: Syntax error in SQL statement "UPDATE ?[*] SET ? = ? WHERE ID = ? "; expected "identifier"; SQL statement:
UPDATE ? SET ? = ? where ID = ? [42001-196]
What is this >>> [*]?
What does it mean?
String sql = "UPDATE " + tableNamer + " SET " + column + " = ? where ID = ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, value);
ps.setInt(2, id);
ps.executeUpdate();
ps.close();
conn.close();
The placeholders can only be used for values in most SQL databases, not for identifiers like table or column names:
"UPDATE myTable SET myCol = ? where ID = ?" -- OK
"UPDATE ? SET ? = ? where ID = ?" -- not OK
The reason is that those parameters are also used for prepared statements, where you send the query to the database once, the database "prepares" the statement, and then you can use this prepared statement many times with different value parameters. this can improve DB performance because DB can compile and optimize the query and then use this processed form repeatedly - but to be able to do this, it needs to know names of the tables and columns involved.
To fix this, you only leave the ?s in for the values, and you concatenate the tableNamer and column manually:
"UPDATE " + tableNamer + " SET " + column + " = ? where ID = ?"
Keep in mind though that by doing this, tableNamer and column are now potentially vulnerable to SQL injection. Make sure that you don't allow user to provide or affect them, or else sanitize the user input.
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.
I'm working with a MySQL-Server and I'm trying to select an ID from another table and insert that ID in a table but it doesn't work all the time.
Code:
public void submit() throws Exception {
Connection connection = getConnection();
Statement stmt = connection.createStatement();
Statement stmt1 = connection.createStatement();
ResultSet asset_id = stmt.executeQuery("SELECT id FROM cars.asset_type WHERE asset_type.name =" + "'" + sellables.getValue()+ "'");
while (asset_id.next()) {
System.out.println(asset_id.getInt("id"));
}
double value = parseDouble(purchased.getText());
System.out.println(value);
LocalDate localDate = purchased_at.getValue();
String insert = "INSERT INTO asset (type_id, purchase_price, purchased_at) VALUES ('"+ asset_id + "','" + value +"','" + localDate +"')";
stmt1.executeUpdate(insert);
}
I keep getting the same error message.
Caused by: java.sql.SQLException: Incorrect integer value: 'com.mysql.cj.jdbc.result.ResultSetImpl#1779d92' for column 'type_id' at row 1
There's no value in doing two client/server roundtrips in your case, so use a single statement instead:
INSERT INTO asset (type_id, purchase_price, purchased_at)
SELECT id, ?, ?
FROM cars.asset_type
WHERE asset_type.name = ?
If you really want to insert only the last ID from your SELECT query (as you were iterating the SELECT result and throwing away all the other IDs), then use this query instead:
INSERT INTO asset (type_id, purchase_price, purchased_at)
SELECT id, ?, ?
FROM cars.asset_type
WHERE asset_type.name = ?
ORDER BY id DESC -- I guess? Specify your preferred ordering here
LIMIT 1
Or with the JDBC code around it:
try (PreparedStatement s = connection.prepareStatement(
"INSERT INTO asset (type_id, purchase_price, purchased_at) " +
"SELECT id, ?, ? " +
"FROM cars.asset_type " +
"WHERE asset_type.name = ?")) {
s.setDouble(1, parseDouble(purchased.getText()));
s.setDate(2, Date.valueOf(purchased_at.getValue()));
s.setString(3, sellables.getValue());
}
This is using a PreparedStatement, which will prevent SQL injection and syntax errors like the one you're getting. At this point, I really really recommend you read about these topics!
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, ...);