Search code examples
javaprepared-statement

Java prepairedStatement setInt is adding quotes in the SQL


I have a simple SQL statement that I want to execute via

        String tokenInsQ = "INSERT INTO pitweb.tokens (token_user_id,token_token,token_valid,token_refresh) (?,?,?,?)";
        try {
            PreparedStatement p = SQL.dbConnection.prepareStatement(tokenInsQ);
            p.setInt(1, r.getInt("user_id").intValue());
            p.setString(2, token.getString("token"));
            p.setTimestamp(3, (Timestamp)token.get("valid"));
            p.setTimestamp(4, (Timestamp)token.get("renew"));
            System.out.println(p);
            p.executeUpdate();      
            p.close();
        } 

I expect this to work just fine. Token is a long string and r.getInt("user_id").intValue() Returns 11. The error I keep getting is

org.postgresql.util.PSQLException: ERROR: syntax error at or near "$1"
  Position: 82 

So I added the print statement to see the SQL that it is trying to execute. The program Prints.

INSERT INTO pitweb.tokens (token_user_id,token_token,token_valid,token_refresh) ('11','really long string ','2020-03-17 13:15:22.847000 -05:00','2020-03-14 13:15:22.847000 -05:00')

I assume that my problem is that the token_user_id ('11') is in quotes. Is this because of the way that I created the Prepared Statement? or do I have a different problem. the output seems vague to me

Here is what the token table looks like

CREATE TABLE pittweb.token
(
    token_id integer NOT NULL DEFAULT nextval('pittweb.token_token_id_seq'::regclass),
    toekn_user_id integer,
    token_valid timestamp without time zone,
    toekn_refresh timestamp without time zone,
    token_token text COLLATE pg_catalog."default",
    CONSTRAINT token_pkey PRIMARY KEY (token_id),
    CONSTRAINT token_toekn_user_id_fkey FOREIGN KEY (toekn_user_id)
        REFERENCES pittweb."user" (user_id) MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION
)
WITH (
    OIDS = FALSE
)

Solution

  • There is a typo in toekn_refresh as well along with toekn_user_id.