0

I have derby database with table TRIPS. I have 10 columns, but 2 columns:FAIR and TIP should be inserted separately (later when trip on taxi is finished).

Can you please help me to adjust SQL code?

I have this code and it is not working now:

public boolean saveInDB2(String id, String amount, String tip) {
        String writeString = "INSERT INTO TRIPS(FAIR, TIP) VALUES ('" + amount +"', '"+ tip +"')" + "WHERE ID = '"+ id +"'";
        try {
            st.executeUpdate(writeString);
        } catch (SQLException sqle){
            return false;
        }
        return true;
    }
Anna
  • 1
  • 1
  • 4
  • 4
    what is the error you are getting? If you're *inserting* twice, that's not an insert on the 2nd run, it's an *update* – sleepToken Nov 27 '19 at 18:51
  • 3
    Don't concatenate strings. Use parameters (`?`) instead. Otherwise, your code can be weak and susceptible to SQL Injection. – The Impaler Nov 27 '19 at 19:17
  • How to correct use parameter "?" – Anna Nov 27 '19 at 19:25
  • sleepToken, I'm not getting any errors. And connection is ok. I'm able to INSERT other data for other columns – Anna Nov 27 '19 at 19:26
  • I am pretty sure that this is not an error but a security warning. To create secure SQL Statements your queries should rely on Preparedstatements. You can find some Details here: https://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html – eckad158 Nov 27 '19 at 19:41
  • Anna, can you teel us what are you trying to archieve? I guess you need to perform two separated queries, one for insert and other for update. To your information using insert into () values () doesn't goes with a where clause, you are mixing things wrong. An insert with where clause is more like this: https://www.w3schools.com/sql/sql_insert_into_select.asp. Also consider this: https://stackoverflow.com/questions/485039/mysql-insert-where-query. Finally (in order to recap) you can read this: https://www.dofactory.com/sql/insert
    – Victor Nov 27 '19 at 20:28
  • 1
    https://www.mkyong.com/jdbc/jdbc-preparestatement-example-insert-a-record/ –  Nov 27 '19 at 21:26

1 Answers1

1

Typically for an existing row, you wouldn't use an INSERT, but rather would use an UPDATE statement. INSERT statements are for new records.

Insert: https://www.w3schools.com/sql/sql_insert.asp Update: https://www.w3schools.com/sql/sql_update.asp