我目前正在使用Google Apps脚本开发数据提取插件。主要思想是应用程序的用户可以将工作表中的数据插入数据库。为此,我正在使用应用程序脚本提供的JDBC API。

我目前遇到的问题是,当我从工作表为空的应用程序脚本读取单元格时,该脚本使用的类型为undefined,因此在插入时会产生错误。我该怎么做?

我当前的插入函数:

function putData(row, tableName) {
  var connectionName = '****';
  var user = '****';
  var userPwd = '*****';
  var db = '******';

  var dbUrl = 'jdbc:google:mysql://' + connectionName + '/' + db;
  var conn = Jdbc.getCloudSqlConnection(dbUrl, user, userPwd);

  var stmt = conn.createStatement();
  var data = row
  var query = "INSERT INTO "+ db + '.' + tableName +" VALUES (" ;
  var i = 0

  //The following loop is just to build the query from the rows taken from the sheet
  // if the value is a String I add quotation marks
  for each (item in row){
    if ((typeof item) == 'string'){
      if (i == row.length-1){
        query += "'" + item + "'";
      } else {
        query += "'" + item + "',";
      }
    }else {
      if (i == row.length-1){
        query += item;
      } else {
        query += item + ",";
      }
    }
  i++
  }
  query += ")"
  results = stmt.executeUpdate(query)
  stmt.close();
  conn.close();
}


在某些情况下,我尝试插入单词“ NULL”时认为是字符串,并在其他字段上显示错误。

最佳答案

尝试从电子表格(更确切地说是从单元格)获取数据时,该值将自动解析为以下类型之一:NumberBooleanDateString

根据Google getValues() documentation


  值的类型可以为NumberBooleanDateString,具体取决于单元格的值。空单元格由数组中的空字符串表示。


因此,从本质上讲,undefined类型可能是您传递row参数的方式中存在的问题(例如,尝试访问超出范围的单元格)。

如果要解决问题,则应在if行之后添加for each (item in row) {语句:

if (typeof item == 'undefined')
  item = null;


if语句检查row内容是否为undefined类型,如果是,它将自动将其解析为null。这样,内容将为null类型,您应该可以将其插入数据库中。

推荐的实际操作方式是使用JDBC Prepared Statements,它们基​​本上是预编译的SQL语句,使您可以轻松插入必要的数据。更准确地说,您无需像上面提供的代码中那样手动为插入准备数据。它们也是更安全的方法,使您的数据不易受到各种攻击。

此外,for each...in语句已被弃用,您应该考虑使用其他内容,例如for循环或while循环。

此外,我建议您看一下这些链接,因为它们可能会有所帮助:


Class JdbcPreparedStatement;
Class Range Apps Script - getValues()

09-25 18:11
查看更多