Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between .query() and .execute() in MySQL

I'm having difficulty comprehending the implementation of prepared statements. I've done a fair amount of research but most of the information I found is either out of context or contain examples far more complex than what I'm trying to accomplish. Can anyone clarify for me why the execute method in the second example below is throwing a syntax error?

NOTE: I'm using the node-mysql2 package here.

controller.js (using query mysql method)

  const db = require("../lib/database");


  async addNewThing(req, res, next) {

    let data = req.body

    const queryString = 'INSERT INTO table SET ?'
    try {
      await db.query(queryString, data)
      res.status(201).json({
        message: 'Record inserted',
        data
      })
    } catch (error) {
      next(error)
    }
  }

Record is successfully inserted into the database


controller.js (using execute mysql method)

  const db = require("../lib/database");


  async addNewThing(req, res, next) {

    let data = req.body

    const queryString = 'INSERT INTO table SET ?'
    try {
      await db.execute(queryString, [data])
      res.status(201).json({
        message: 'Record inserted',
        data
      })
    } catch (error) {
      next(error)
    }
  }

Results in the following error:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?' at line 1


data

{ thing_id: '987654', thing_name: 'thing' }
like image 779
romeplow Avatar asked Nov 07 '18 21:11

romeplow


1 Answers

With .query(), parameter substitution is handled on the client, including objects which let data = req.body is in the above examples.

With .execute() prepared statement parameters are sent from the client as a serialized string and handled by the server. Since let data = req.body is an object, that's not going to work.

like image 107
romeplow Avatar answered Oct 17 '22 15:10

romeplow