sqlState: '42000' MySql You have an error in your SQL syntax; for the right syntax to use near '?,?,?,?,?,?,?,?)'

677 Views Asked by At

I'm trying to insert values into MySql Database(vesrion 8.0) using postman and I keep getting below error. After reading through some of the blogs I've used backticks(``) for reserved words table/column names, unfortunately it didn't help me and i'm still getting same error. I'm using mysql2 lib

Error

Incoming POST /patients Request from Content-Type text/plain
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
    at PromisePool.query (C:\Users\thota01\NodeApi\NodejsApi\node_modules\mysql2\promise.js:341:22)
    at C:\Users\thota01\NodeApi\NodejsApi\src\controller\patient.controller.ts:53:45
    at Generator.next (<anonymous>)
    at fulfilled (C:\Users\thota01\NodeApi\NodejsApi\src\controller\patient.controller.ts:5:58)
    at processTicksAndRejections (internal/process/task_queues.js:95:5) {
  code: 'ER_PARSE_ERROR',
  errno: 1064,
  sql: 'INSERT INTO `patients` (`first_name`, `last_name`, `email`, `address`, `diagnosis`, `phone`, `status`, `image_url`) VALUES(?,?,?,?,?,?,?,?)',
  sqlState: '42000',
  sqlMessage: "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"
}

Code controller.ts

import { Request, Response } from "express"
import { FieldPacket, OkPacket, ResultSetHeader, RowDataPacket } from "mysql2";
import { connection } from "../config/mysql.config";
import { HttpResponse } from "../domain/response";
import { Code } from "../enum/code.enum";
import { Status } from "../enum/status.enum";
import { patients } from "../interface/patients";
import { QUERY } from "../query/patient.query";

type ResultSet = [RowDataPacket[] | RowDataPacket[][] | OkPacket | OkPacket[] | ResultSetHeader, FieldPacket[]]



export const getPatients = async(req:Request, res:Response):Promise<Response<patients[]>> =>{
    console.info(`[${new Date().toLocaleString()}] Incoming ${req.method} ${req.originalUrl} Request from ${req.rawHeaders[0]} ${req.rawHeaders[1]}`);
    try{
        const pool = await connection();
        const result:ResultSet = await pool.query(QUERY.SELECT_PATIENTS);
        return res.status(Code.OK)
                  .send(new HttpResponse(Code.OK,Status.OK, 'Patient Retrived' , result[0]));
    } catch(error:unknown){
            console.error(error) 
        return res.status(Code.INTERNAL_SERVER_ERROR)
               .send(new HttpResponse(Code.INTERNAL_SERVER_ERROR,Status.INTERNAL_SERVER_ERROR, 'An Error Occurred '));
    }
};

export const getPatient = async(req:Request, res:Response):Promise<Response<patients>> =>{
    console.info(`[${new Date().toLocaleString()}] Incoming ${req.method} ${req.originalUrl} Request from ${req.rawHeaders[0]} ${req.rawHeaders[1]}`);
    try{
        const pool = await connection();
        const result:ResultSet = await pool.query(QUERY.SELECT_PATIENT , [req.params.patientId]);
        if((result[0] as Array<ResultSet>).length>0){
            return res.status(Code.OK)
            .send(new HttpResponse(Code.OK,Status.OK, 'Patient Retrived' , result[0]));
        }else{
            return res.status(Code.NOT_FOUND)
                   .send(new HttpResponse(Code.NOT_FOUND,Status.NOT_FOUND, 'Patient NOT Found'));
        }

    } catch(error:unknown){
        console.error(error)
        return res.status(Code.INTERNAL_SERVER_ERROR)
               .send(new HttpResponse(Code.INTERNAL_SERVER_ERROR,Status.INTERNAL_SERVER_ERROR, 'An Error Occurred '));
    }
};

export const createPatient = async(req:Request, res:Response):Promise<Response<patients>> =>{
    console.info(`[${new Date().toLocaleString()}] Incoming ${req.method} ${req.originalUrl} Request from ${req.rawHeaders[0]} ${req.rawHeaders[1]}`);
    let Patient:patients = {...req.body}
    try{
        const pool = await connection();
        const result:ResultSet = await pool.query(QUERY.CREATE_PATIENT , Object.values(Patient));
        Patient ={ id : (result[0] as ResultSetHeader).insertId,...req.body}        
            return res.status(Code.CREATED)
            .send(new HttpResponse(Code.CREATED,Status.CREATED, 'Patient Created' , Patient));
        }

     catch(error:unknown){
        console.error(error)
        return res.status(Code.INTERNAL_SERVER_ERROR)
               .send(new HttpResponse(Code.INTERNAL_SERVER_ERROR,Status.INTERNAL_SERVER_ERROR, 'An Error Occurred '));
    }
};

export const updatePatient = async(req:Request, res:Response):Promise<Response<patients>> =>{
    console.info(`[${new Date().toLocaleString()}] Incoming ${req.method} ${req.originalUrl} Request from ${req.rawHeaders[0]} ${req.rawHeaders[1]}`);
    let Patient:patients = {...req.body}
    try{
        const pool = await connection();
        const result:ResultSet = await pool.query(QUERY.SELECT_PATIENT , [req.params.patientId]);
        if((result[0] as Array<ResultSet>).length>0){
            const result:ResultSet = await pool.query(QUERY.UPDATE_PATIENT , [...Object.values(Patient),req.params.patientId]);
            return res.status(Code.OK)
            .send(new HttpResponse(Code.OK,Status.OK, 'Patient Updated' , {...Patient,id:req.params.patientId}));
        }else{
            return res.status(Code.NOT_FOUND)
                   .send(new HttpResponse(Code.NOT_FOUND,Status.NOT_FOUND, 'Patient NOT Found'));
        }

    } catch(error:unknown){
        console.error(error)
        return res.status(Code.INTERNAL_SERVER_ERROR)
               .send(new HttpResponse(Code.INTERNAL_SERVER_ERROR,Status.INTERNAL_SERVER_ERROR, 'An Error Occurred '));
    }
};

export const deletePatient = async(req:Request, res:Response):Promise<Response<patients>> =>{
    console.info(`[${new Date().toLocaleString()}] Incoming ${req.method} ${req.originalUrl} Request from ${req.rawHeaders[0]} ${req.rawHeaders[1]}`);
   
    try{
        const pool = await connection();
        const result:ResultSet = await pool.query(QUERY.SELECT_PATIENT , [req.params.patientId]);
        if((result[0] as Array<ResultSet>).length>0){
            const result:ResultSet = await pool.query(QUERY.DELETE_PATIENT , [req.params.patientId]);
            return res.status(Code.OK)
            .send(new HttpResponse(Code.OK,Status.OK, 'Patient Deleted' ));
        }else{
            return res.status(Code.NOT_FOUND)
                   .send(new HttpResponse(Code.NOT_FOUND,Status.NOT_FOUND, 'Patient NOT Found'));
        }

    } catch(error:unknown){
        console.error(error)
        return res.status(Code.INTERNAL_SERVER_ERROR)
               .send(new HttpResponse(Code.INTERNAL_SERVER_ERROR,Status.INTERNAL_SERVER_ERROR, 'An Error Occurred '));
    }
};

PatientQuery.ts

export const QUERY =  {
    SELECT_PATIENTS : 'SELECT * FROM patients ORDER BY created_at DESC LIMIT 50',
    SELECT_PATIENT : 'SELECT * FROM patients WHERE id = ?',
    CREATE_PATIENT : 'INSERT INTO patients (first_name,last_name,email, address,diagnosis,phone,status,image_url) values(?, ?, ?, ?, ?, ?, ?, ?)',
    UPDATE_PATIENT : 'UPDATE patients set first_name = ?, last_name = ? ,email = ?, address = ?,diagnosis = ?,phone = ?,status = ?,image_url = ? WHERE id= ?',
    DELETE_PATIENT : 'DELETE FROM patients WHERE id= ?'
}
0

There are 0 best solutions below