【问题标题】:Send DBNull.Value instead of 'null' in nodeJS MySql在 nodeJS MySql 中发送 DBNull.Value 而不是“null”
【发布时间】:2014-09-27 21:01:58
【问题描述】:

如何在 node.js 中向数据库发送空值? 我正在使用MySql Package for node JS

我有一些空值要插入,我想将它们作为 DBNull.Value(在 asp.net 中)而不是“null”或“”存储在数据库中。

另外,我不能跳过任何要插入的值。

我的代码如下:

var query=connection.query("insert into user_details(user_id,username,screenname,firstname,middlename,lastname,about_me,color_code,Gender,hobbies,occupation,member_of_group,profile_pic,address1,address2,city,pincode,phonenumber,EmailId1,EmailId2,createdate,updatedate) values('"+json.user_id+"','"+ json.username+"','"+json.screenname+"','"+json.firstname+"','"+json.middlename+"','"+json.lastname+"','"+json.about_me+"','"+json.color_code+"','"+json.Gender+"','"+json.hobbies+"','"+json.occupation+"','"+json.member_of_group+"','"+json.profile_pic+"','"+json.address1+"','"+json.address2+"','"+json.city+"',"+json.pincode+",'"+json.phonenumber+"','"+json.EmailId1+"','"+json.EmailId2+"','"+json.createdate+"','"+json.updatedate+"');",function(err,result){
       if(!err){
        connection.destroy();
        callback(result);
       }
       else
       {
          console.log(err);
          callback('error');
       }
});

我该怎么做???

【问题讨论】:

    标签: javascript mysql node.js node-mysql


    【解决方案1】:

    首先,出于安全原因,您不应该直接连接(尤其是用户提交的)值,而且当您进行大量连接时,这会很乏味。

    试试这个,它可以更轻松地使用并正确转义您的值:

    connection.query('INSERT INTO user_details SET ?', json, function(err, result) {
      connection.destroy();
      if (err)
        console.log(err);
      callback(err, result);
    });
    

    如果数据源中的键与列名不匹配,则手动指定值:

    var values = {
      user_id: json.id,
      username: json.user,
      // ...
    };
    connection.query('INSERT INTO user_details SET ?', values, function(err, result) {
      connection.destroy();
      if (err)
        console.log(err);
      callback(err, result);
    });
    

    其次,通常回调使用“错误优先”,因此将真正的错误对象作为第一个参数传递会更好。

    【讨论】:

    • +1 感谢您的及时回复,但它也发送“空”字符串值而不是 DBNull 对象
    • 感谢您的宝贵建议。我已经修复了我的代码。 :)
    • 我不确定我是否理解。当你传入一个值为空的值时,console.dir(json.somenullproperty) 会输出什么?它是否显示null'null' 或其他内容?
    • null for err 表示没有错误,通常没有result for INSERT/UPDATE/DELETE 因为它们不返回行。跨度>
    猜你喜欢
    • 1970-01-01
    • 2015-10-28
    • 2011-11-24
    • 1970-01-01
    • 2021-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多