Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't send the value of null to MySQL database using Node.JS

I'm trying to send null to my MySQL database using Node.JS:

con.query("INSERT INTO Routes (routeTrigger) VALUES ( " + null + " )", {title: 'test'}, function(err, result) {
    if (err) throw err;
});

But when looking in the database, the updated value reads 'null'. The database's NULL is supposed to read NULL. If I send capital NULL instead, that doesn't even work (in Node.JS). If I send 'NULL' it sends the string "NULL", and not the database's NULL.

like image 814
djokerndthief Avatar asked Sep 07 '17 22:09

djokerndthief


2 Answers

JavaScript's null is not the same as SQL's Null. You want (in your case, using raw SQL strings) a string:

con.query("INSERT INTO Routes (routeTrigger) VALUES ( null )", {title: 'test'}, function(err, result) {
    if (err) throw err;
});

But note that that creates a row that's entirely null. Which is possible, but it's unlikely what you want.

What are you actually trying to do?

like image 57
tpdi Avatar answered Oct 08 '22 19:10

tpdi


If you want to assign the NULL value In the SQL tables, you can think differently.

Instead of assigning NULL, you can tweak the field (column) so that the default value (when no value is assigned) is : NULL.

Now, when you insert your new row, just don't assign any value to that field.


Example :

Let's say the table is structured like so :

MyTable

id: auto increment; ...

name: text

url: text; default = NULL

Then you could do:

INSERT INTO Mytable ( name ) VALUES ( "Joe" );

As you omit the url information, it gets set to NULL.

like image 26
Bird Avatar answered Oct 08 '22 18:10

Bird