skip to Main Content

I have a typescript and DB question. I generate a uuid as a ticket like so and I can see when I console log it, it displays the uuid as expected.

I then want to take that param value and insert it into the database. However, I notice in the DB instead of showing the uuid value, it is displaying a ‘?’. How do I add a param value into the DB?

const ticketId: string = uuidv4(); //632d8ea6-ff67-4069-b97c-8c23aa0104dd

await addItem(ticketId);

export function addItem(ticketId: string) {

  const query = sql`INSERT INTO test.ticket (ticket.uuid)
  VALUES ("${ticketId}")`;
  console.log(query);
  return execute(query);
}

console log shows this:

{
      text: 'INSERT INTO test.ticket (ticket.uuid)n' +
        '  VALUES ("$1",)',
      sql: 'INSERT INTO test.ticket (ticket.uuid)n' +
        '  VALUES ("?")',
      values: [ '632d8ea6-ff67-4069-b97c-8c23aa0104dd' ]
}

Screenoshot of mysql workbench showing the db row:
enter image description here

2

Answers


  1. Chosen as BEST ANSWER

    Figured it out, ensure there is no quotation around the param. So it should be:

    const query = sql`INSERT INTO test.ticket (ticket.uuid)
      VALUES (${ticketId})`;
    

    NOT

    const query = sql`INSERT INTO test.ticket (ticket.uuid)
      VALUES ("${ticketId}")`;
    

  2. It’s a parameterized query to the DB.
    It has some pros.

    1. Guard from sql injections as the real value arrive from a specific parameter it’s harder to tweek it to run other code.
    2. Performance: when the query is created and compiled in the sql instance, the next time you will use the same query it will be already optimized and the engine doesn’t have to compile it again.

    What you need to check is what will return from a fetch query.
    Like this one:

    select * from test.ticket 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search