Google Apps脚本写入JDBC数据库

时间:2013-01-25 15:11:20

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

我需要一些关于如何写入和读取MS SQL数据库的语法的帮助。

我想出了连接字符串,现在我只需要一些关于如何写入数据库并从中读取的帮助。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

以下是一些用于编写(然后获取ID),简单标量读取和表格读取的简单示例。

function write() {
  var conn = Jdbc.getCloudSqlConnection("jdbc:google:rdbms://your-connection-string-helloworld/mysql");
  var stmt = conn.createStatement();
  var sql = "INSERT INTO animals (name) VALUES ('lion')";
  var count = stmt.executeUpdate(sql,1)//pass in any integer to get auto incremented IDs back
  //check to see any auto generated keys come back. that is optional. 
  var rs = stmt.getGeneratedKeys();
  while(rs.next()) {
    Logger.log(rs.getString(1));
  }
  rs.close();
  stmt.close();
  conn.close();
}


function read() {
var conn = Jdbc.getCloudSqlConnection("jdbc:google:rdbms://your-connection-string-helloworld/mysql");
  var stmt = conn.createStatement();
  var rs = stmt.executeQuery("select * from animals");

  var doc = SpreadsheetApp.create('gdg test');
  var cell = doc.getRange('a1');
  var row = 0;
  while(rs.next()) {
    cell.offset(row, 0).setValue(rs.getString(1));
    cell.offset(row, 1).setValue(rs.getString(2));
    row++;
  }
  rs.close();
  stmt.close();
  conn.close();
}

function simpleRead() {
  var conn = Jdbc.getCloudSqlConnection("jdbc:google:rdbms://your-connection-string-helloworld/mysql");
  var stmt = conn.createStatement();
  var rs = stmt.executeQuery("select database()");
  rs.next(); //if you expect multiple rows, then do this in while(rs.next()) loop
  Logger.log(rs.getString(1));
  rs.close();
  stmt.close();
  conn.close();
}