根据Google表格中“命名范围”中的数据在Google Cloud SQL中创建表

时间:2018-07-12 22:32:22

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

我在一个Google电子表格中有多个命名范围。我需要在Google Cloud SQL中为每个命名范围创建一个表,其中包含各自命名范围中的数据

为此我开发了以下Google Apps脚本。但是我很好奇,是否有更好的方法可以通过Google Apps Script或其他方式实现这一目标。我愿意接受想法。

  var conn = Jdbc.getConnection(dbUrl, user, userPwd);

  var colNames = rangeValues[0];
  var sampleRow = rangeValues[2]

  var CREATE_TABLE_STATEMENT = " CREATE TABLE " + tableName + "(";

  var COLUMNS_TYPES= Array();
  var UntitledColumnName = 1;
  for (var colNames_i = 0; colNames_i < colNames.length; colNames_i++) {
    var colName = colNames[colNames_i];
    if (typeof sampleRow[colNames_i] == "number") {
      COLUMNS_TYPES[colNames_i] = "number";
      if (colName != "") {
        CREATE_TABLE_STATEMENT += " `" + colName + "` INT,";
      }
      else {
        CREATE_TABLE_STATEMENT += " " + "Column" + UntitledColumnName + " INT,";
        UntitledColumnName++;
      }
    }
    else {
      COLUMNS_TYPES[colNames_i] = 'string';
      if (colName != "") {
        CREATE_TABLE_STATEMENT += " `" + colName + "` VARCHAR(255),";
      }
      else {
        CREATE_TABLE_STATEMENT += " " + "Column" + UntitledColumnName +   " VARCHAR(255),";
        UntitledColumnName++;
      }
    }
  }

  CREATE_TABLE_STATEMENT = CREATE_TABLE_STATEMENT.slice(0, -1);
  CREATE_TABLE_STATEMENT += ")"
  Logger.log(CREATE_TABLE_STATEMENT);

  var stmt = conn.prepareStatement(CREATE_TABLE_STATEMENT); 
  stmt.execute();
  //   conn.setAutoCommit(false);

  for (var row_i = 1; row_i < rangeValues.length; row_i++) {
    var INSERT_STATEMENT = "INSERT INTO " + tableName + " values (";
    for (var colNames_i = 0; colNames_i < colNames.length; colNames_i++){
      if (COLUMNS_TYPES[colNames_i] == "number") {
        INSERT_STATEMENT +=  rangeValues[row_i][colNames_i] + ",";
      }
      else {
        INSERT_STATEMENT +=  "'" + rangeValues[row_i][colNames_i] + "',";
      }
    }

    INSERT_STATEMENT = INSERT_STATEMENT.slice(0, -1);
    INSERT_STATEMENT += ")"

    Logger.log(INSERT_STATEMENT);
    var stmt = conn.prepareStatement(INSERT_STATEMENT);
    try {
      stmt.execute();
    }
    catch(e){}
  }

0 个答案:

没有答案