根据 Google Sheets Apps 脚本中的 ID 更新 MySQL 行

问题描述 投票:0回答:1

我正在寻找从 Google Sheet 更新 MySQL 数据库的行。我当前的工作流程是将现有表格导入 Google 表格中的一张表格中,将其复制到另一张表格中进行更改,然后运行新脚本来更新表格。

我可能可以更有效地做到这一点,但这样做意味着我无法自动执行任何操作,并且有破坏数据库的风险。

我创建了一个脚本,我只更新一列,它可以工作,除了在我的数据库中,id 列不是连续的,因为记录已被删除(例如,它从第 3 行开始,然后是第 5,6,7,9 行等)。但我的脚本没有考虑到这一点,只会使用 Google Sheets 行 ID 来匹配它(例如,在 MySQL 中,第一行是第 3 行,但在 Google Sheets 中,它将是第 1 行)。这意味着存在不匹配。

我的脚本如下,我一直在修补,但似乎无法使其工作。唯一 ID 位于 A 列中。

另一件事是,我认为我的循环效率不高,因为数据库将增长到超过 400 行。

function UpdateDB(e) {

 
  ss = SpreadsheetApp.getActiveSpreadsheet();
  sheet = ss.getSheetByName("writeSheet");
  hookn = sheet.getRange("M2:M300").getDisplayValues() ;
  uid = sheet.getRange("A2:A300").getDisplayValues() ;
  
  server = "1******";
  port = '3306';
  dbName =  "*****";
  username = "*******";
  password = "*********";
  url = "jdbc:mysql://" + server + ":" + port + "/" + dbName + "?characterEncoding=UTF-8";

  conn = Jdbc.getConnection(url, username, password);
  stmt = conn.createStatement();

  for (i=0 ; i<400 ; i++ ) {  
    stmt.execute("UPDATE wp_tripetto_forms SET hooks ='" + hookn[i] + "' WHERE id = " + (i+1) + " ;");
  }


  conn.close();
}

虽然行确实更新,但由于脚本使用 Google Sheet 行 ID 作为 MySQL 唯一 ID,ID 不正确。

javascript mysql google-apps-script jdbc
1个回答
0
投票

这就是我让它工作的方法:

function UpdateDB(e) {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sheet = ss.getSheetByName("writeSheet");
  const hookn = sheet.getRange("M2:M" + sheet.getLastRow()).getDisplayValues().flat();
  const uid = sheet.getRange("A2:A" + sheet.getLastRow()).getDisplayValues().flat();

  const server = "1******";
  const port = '3306';
  const dbName = "*****";
  const username = "*******";
  const password = "*********";
  const url = "jdbc:mysql://" + server + ":" + port + "/" + dbName + "?characterEncoding=UTF-8";

  const conn = Jdbc.getConnection(url, username, password);
  const stmt = conn.createStatement();

  // Retrieve all IDs from the MySQL table
  const resultSet = stmt.executeQuery("SELECT id FROM wp_tripetto_forms");
  const ids = [];
  while (resultSet.next()) {
    ids.push(resultSet.getInt("id"));
  }

  // Update the rows using the retrieved IDs
  for (let i = 0; i < ids.length; i++) {
    const id = ids[i];
    const idx = uid.indexOf(id.toString());
    if (idx !== -1) {
      stmt.execute(`UPDATE wp_tripetto_forms SET hooks = '${hookn[idx]}' WHERE id = ${id};`);
    }
  }

  conn.close();
}

© www.soinside.com 2019 - 2024. All rights reserved.