如何在谷歌应用脚​​本中建立连接? [英] How to pool a connection in google apps script?

查看:150
本文介绍了如何在谷歌应用脚​​本中建立连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此前,在 Google Apps脚本的脚本中,我打开并关闭了所有功能中的Jdbc连接。

为了加速我的应用程序,似乎最好断开连接并将其用于其他功能。但是,我不知道该如何在 Google Apps脚本中执行此操作。



任何人都可以给我一个建议或示例吗?

解决方案

以下是如何在ScriptDB中保留连接的示例。



< pre-class =lang-js prettyprint-override> function myFunction(){
var conn = ScriptDb.getMyDb()。query({name:my_connection});
var connection = null;
var itemId = null;如果(conn.getSize()== 0){
Logger.log(未找到连接,创建新连接);

if
connection = Jdbc.getConnection('jdbc:mysql://< host>:3306 /< instance>','user','password');
itemId = ScriptDb.getMyDb()。save({name:my_connection,connection:connection})。getId();
$ b} else {
Logger.log(发现连接,检索+ conn.getSize());
var dbItem = conn.next();
connection = dbItem.connection;
itemId = dbItem.getId();
}

//检查它是否已关闭
if(connection.isClosed()){
connection = Jdbc.getConnection('jdbc:mysql:// < host>:3306 /< instance>','user','password');

//打开后记得再保存到dabatase并保留一个连接
ScriptDb.getMyDb()。removeById(itemId);
ScriptDb.getMyDb()。save({name:my_connection,connection:connection});
}

//在这里使用你的连接

// Remenber根据一些标准关闭它
}

示例这里


Previously in scripting in Google Apps Script, I opened and closed my Jdbc connection in all the functions.

In order to speed up my application, it seems to be better to leave the connection open and use it in another function. However, I don't know how I should do that in Google Apps Script.

Can anyone give me a suggestion or an example?

解决方案

Here is an example of how to retain your connection at ScriptDB.

function myFunction() {
  var conn = ScriptDb.getMyDb().query({name : "my_connection"} );
  var connection = null;
  var itemId = null;

  if(conn.getSize() == 0) {
    Logger.log(" Connection not found, creating new one");
    connection = Jdbc.getConnection('jdbc:mysql://<host>:3306/<instance>', 'user', 'password');
    itemId = ScriptDb.getMyDb().save({name : "my_connection", connection : connection}).getId();

  }else {
    Logger.log(" Connection found, retrieving "+conn.getSize());
    var dbItem  = conn.next();
    connection = dbItem.connection;
    itemId = dbItem.getId();
  }

  //Check if it is closed
  if(connection.isClosed()) {
    connection = Jdbc.getConnection('jdbc:mysql://<host>:3306/<instance>', 'user', 'password');

    //After opening remember to save to dabatase again and retain only one connection
    ScriptDb.getMyDb().removeById(itemId);
    ScriptDb.getMyDb().save({name : "my_connection", connection : connection});
  }

  //Use your connection here

  //Remenber to close it based in some criteria
}

Example here.

这篇关于如何在谷歌应用脚​​本中建立连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆