Ошибка модуля mysjl nodejs при вставке строки

У меня возникла проблема при попытке вставить строку в мою базу данных.

Вот структура моей таблицы:

mysql> describe emprunt;
+------------------+---------+------+-----+---------+----------------+
| Field            | Type    | Null | Key | Default | Extra          |
+------------------+---------+------+-----+---------+----------------+
| idEmprunt        | int(11) | NO   | PRI | NULL    | auto_increment |
| Joueur_idEmprunt | int(11) | NO   |     | NULL    |                |
| valeur_empruntee | float   | NO   |     | NULL    |                |
| duree_emprunt    | int(11) | NO   |     | NULL    |                |
| jour_emprunt     | int(3)  | NO   |     | NULL    |                |
| mois_emprunt     | int(3)  | NO   |     | NULL    |                |
+------------------+---------+------+-----+---------+----------------+

Моя программа должна сделать следующее: клиент откроет HTML-страницу, на которой есть кнопка. При нажатии данные отправляются на сервер, чтобы добавить строку в мою таблицу.

Я даю вам весь код, чтобы вы могли понять, но вы должны сосредоточиться на последних строках, функции setEmprunt(..), потому что именно там происходит ошибка.

var server = require('http').createServer(function(req, res){
        res.end('chargement effectué');
    });
server.listen(8080);    

var io = require('socket.io').listen(server);

var mysql = require('mysql');
//using a pool to manage multi users queries
var pool = mysql.createPool({
    host     : 'localhost',
    user     : 'NoNeedToKnowThat', 
    password : 'Neither', 
    database : 'test' //
});

//A client open the HTML page
io.sockets.on('connection', function (socket) {
    console.log('Client !!');



    //===================================================
    // Client clicks the button and sends 2, 7000, 15
    //===================================================
    socket.on('setEmprunt', function (aIdJoueur, aSomme, aDuree) {

        pool.getConnection(function(err, connection) {

            setEmprunt(connection, aIdJoueur, aSomme, aDuree, function(err){
                if(err) {
                    console.log("error in setEmprunt : "+ err);
                    throw err;
                }
                else
                    console.log("callback of setEmprunt");
            });
            // And done with the connection.
            connection.release();

        });

    }); 


function setEmprunt(aConnection, aIdJoueur, aSomme, aDuree, aCallback){
    var maintenant= new Date(),
        jourEmprunt = maintenant.getDate(),
        moisEmprunt = maintenant.getMonth();
    rowToBeInserted = { Joueur_idEmprunt : aIdJoueur, valeur_empruntee : aSomme, duree_emprunt : aDuree, jour_emprunt : jourEmprunt, mois_emprunt : moisEmprunt };
    console.log("set emprunt de : " + rowToBeInserted);


//There is the problem line
    aConnection.query('INSERT INTO emprunt VALUES ?', rowToBeInserted, aCallback);


}

И вот мой результат:

C:\Users\QuentinB\Developpement>node serveur.js
   info  - socket.io started
   info  - handshake authorized ZIH1OSAUuRGHz8G9hCfc
Client !!
set emprunt de : [object Object]
error in setEmprunt : Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syn
tax to use near '`Joueur_idEmprunt` = 2, `valeur_empruntee` = 7000, `duree_emprunt` = 15, `jour_e' at line 1

Error: ER_PARSE_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 '`Joueur_
idEmprunt` = 2, `valeur_empruntee` = 7000, `duree_emprunt` = 15, `jour_e' at line 1
    at Query.Sequence._packetToError (C:\Users\QuentinB\Developpement\giserv5\node_modules\mysql\lib\protocol\sequences\Sequence.js:30:14)

Я знаю, что это последняя строка моего кода, которая блокирует, потому что я пытался заменить ее на:

aConnection.query('INSERT INTO emprunt(Joueur_idEmprunt, valeur_empruntee, duree_emprunt, jour_emprunt, mois_emprunt) VALUES('+aIdJoueur+','+aSomme+','+aDuree+','+jourEmprunt+','+moisEmprunt+');', aCallback);

и это сработало. Я хотел бы понять, почему не работает aConnection.query('INSERT INTO emprunt VALUES?', RowToBeInserted, aCallback).

Спасибо за помощь.

1 ответ

Решение

Беглый взгляд, я считаю, что вы хотите использовать INSERT INTO...SET ? не INSERT INTO...VALUES ? в вашем коде в этом случае. ? расширяется в name=val пары, в то время как предложение VALUES ищет только значения.

Другие вопросы по тегам