【问题标题】:Inserting Null values to Mysql database from Sheets using Google Apps Script使用 Google Apps 脚本将 Null 值从表格插入 Mysql 数据库
【发布时间】:2019-12-27 20:46:36
【问题描述】:

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

我目前遇到的问题是,当我从工作表中读取一个空的应用程序脚本的单元格时,它使用了未定义的类型,因此在插入时会产生错误。我怎么能做这种事?

我当前的插入函数:

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”时,我认为它是一个字符串并在其他字段上显示错误。

【问题讨论】:

  • 我认为你可以测试它的真实性和类型。如果真实性为假,则插入 null。

标签: mysql sql google-apps-script jdbc google-sheets


【解决方案1】:

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

根据Google getValues() documentation

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

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

如果你想解决你的问题,你应该在for each (item in row) { 行之后添加一个if 语句:

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

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

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

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

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

  1. Class JdbcPreparedStatement;

  2. Class Range Apps Script - getValues().

【讨论】:

  • 效果很好!事实证明它确实返回 '' 而不是“未定义”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-02
相关资源
最近更新 更多