5.数据库插入数据时处理转义符的方法

无意中看到同事写的一段代码,对插入数据的参数进行了一次过滤。感觉这样做蛮好的。可以防止转义符的一些问题。现将其摘录下来,以便以后备用。

function SC (val) {
  if (val === undefined || val === null) {
    return null;
  }
  if (typeof val === 'number') {
    return val+'';
  }
  val = val.replace(/[\0\n\r\b\t\\\'\"\x1a]/g, function(s) {
    switch(s) {
      case "\0": return "\\0";
      case "\n": return "\\n";
      case "\r": return "\\r";
      case "\b": return "\\b";
      case "\t": return "\\t";
      case "\x1a": return "\\Z";
      default: return "\\"+s;
    }
  });
  return "'"+val+"'";
};

 

posted @ 2018-08-23 15:16  想~(●—●)肥~  阅读(880)  评论(0编辑  收藏  举报